name
stringlengths
18
69
filepath
stringclasses
38 values
source
stringclasses
38 values
test
stringlengths
306
10.4k
ShardingPropagationTest_PropagateShardLikeDifferentSharding
xla/service/sharding_propagation_test.cc
std::optional<HloSharding> ReturnImprovedSharding( HloSharding sharding, HloInstruction* instruction, bool may_combine_partial_sharding, bool allow_aggressive_resharding = false) { return hlo_sharding_util::ReturnImprovedShardingImpl( std::move(sharding), instruction->has_sharding() ? &instruction->sharding() : nullptr, instruction->shape(), may_combine_partial_sharding, allow_aggressive_resharding); } std::optional<HloSharding> ReturnImprovedSubSharding( HloSharding sharding, HloInstruction* instruction, const ShapeIndex& index, bool may_combine_partial_sharding, bool allow_aggressive_resharding = false) { if (instruction->has_sharding()) { const HloSharding to_improved = instruction->sharding().GetSubSharding(instruction->shape(), index); return hlo_sharding_util::ReturnImprovedShardingImpl( std::move(sharding), &to_improved, ShapeUtil::GetSubshape(instruction->shape(), index), may_combine_partial_sharding, allow_aggressive_resharding); } else { return hlo_sharding_util::ReturnImprovedShardingImpl( std::move(sharding), nullptr, ShapeUtil::GetSubshape(instruction->shape(), index), may_combine_partial_sharding, allow_aggressive_resharding); } } bool MaybeImproveInstructionSharding(HloSharding sharding, HloInstruction* instruction, bool may_combine_partial_sharding, bool allow_aggressive_resharding = false) { if (auto new_sharding = ReturnImprovedSharding( std::move(sharding), instruction, may_combine_partial_sharding, allow_aggressive_resharding)) { instruction->set_sharding(std::move(*new_sharding)); return true; } return false; } bool MaybeImproveInstructionSubSharding( HloSharding sharding, HloInstruction* instruction, const ShapeIndex& index, bool may_combine_partial_sharding, bool allow_aggressive_resharding = false) { if (instruction->shape().IsTuple()) { if (auto new_sub_sharding = ReturnImprovedSubSharding( std::move(sharding), instruction, index, may_combine_partial_sharding, allow_aggressive_resharding)) { HloSharding new_sharding = instruction->has_sharding() ? instruction->sharding() : HloSharding::Single(instruction->shape(), HloSharding::Replicate()); ShapeTree<HloSharding> sharding_shape_tree = new_sharding.GetAsShapeTree(instruction->shape()); *sharding_shape_tree.mutable_element(index) = new_sub_sharding.value(); instruction->set_sharding(HloSharding::Tuple(sharding_shape_tree)); return true; } else { return false; } } CHECK(index.size() == 1 && index[0] == 0); return MaybeImproveInstructionSharding(std::move(sharding), instruction, may_combine_partial_sharding, allow_aggressive_resharding); } bool IsConvolutionKernelSmall(const HloInstruction* instruction) { CHECK_EQ(instruction->opcode(), HloOpcode::kConvolution); const HloInstruction* rhs = instruction->operand(1); const auto& dnums = instruction->convolution_dimension_numbers(); int64_t kernel_dim_prod = 1; int64_t output_dim_prod = 1; for (int64_t i = 0; i < dnums.input_spatial_dimensions().size(); ++i) { int64_t kernel_dim = rhs->shape().dimensions(dnums.kernel_spatial_dimensions(i)); kernel_dim_prod *= kernel_dim; int64_t output_dim = instruction->shape().dimensions(dnums.output_spatial_dimensions(i)); output_dim_prod *= output_dim; if (kernel_dim >= output_dim && (i < 2 || kernel_dim > 3 || kernel_dim_prod >= output_dim_prod)) { return false; } } return true; } bool IsPassthroughCustomOps(const HloInstruction* hlo) { if (hlo->IsCustomCall({"Sharding", "X64Combine", "LayoutConstraint"})) { return true; } if (hlo->operand_count() != 1 || !hlo->shape().IsArray() || !hlo->operand(0)->shape().IsArray() || hlo->operand(0)->shape().rank() != hlo->shape().rank()) { return false; } return hlo->IsCustomCall( {"ResizeNearest", "ResizeBilinear", "ResizeNearestGrad", "ResizeBilinearGrad", "Cholesky", host_memory_offload_annotations::kMoveToDeviceCustomCallTarget, host_memory_offload_annotations::kMoveToHostCustomCallTarget}); } const HloInstruction* PickRepresentativeOperand( const HloInstruction* instruction) { switch (instruction->opcode()) { case HloOpcode::kMap: case HloOpcode::kPad: case HloOpcode::kPower: case HloOpcode::kOptimizationBarrier: case HloOpcode::kReverse: case HloOpcode::kSlice: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: // For these opcodes the output sharding has to be determined by the // sharding of the first operand but we can only determine sharding based // on it if it already has a sharding. if (instruction->operand(0)->has_sharding()) { return instruction->operand(0); } return nullptr; case HloOpcode::kAbs: case HloOpcode::kAdd: case HloOpcode::kAnd: case HloOpcode::kAtan2: case HloOpcode::kBitcastConvert: case HloOpcode::kCeil: case HloOpcode::kClamp: case HloOpcode::kClz: case HloOpcode::kCompare: case HloOpcode::kComplex: case HloOpcode::kConcatenate: case HloOpcode::kConvert: case HloOpcode::kCopy: case HloOpcode::kCos: case HloOpcode::kAllGather: case HloOpcode::kAllReduce: case HloOpcode::kReduceScatter: case HloOpcode::kAllToAll: case HloOpcode::kCollectiveBroadcast: case HloOpcode::kCollectivePermute: case HloOpcode::kDivide: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kFloor: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kMultiply: case HloOpcode::kNegate: case HloOpcode::kNot: case HloOpcode::kOr: case HloOpcode::kPopulationCount: case HloOpcode::kReal: case HloOpcode::kReducePrecision: case HloOpcode::kRemainder: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kRsqrt: case HloOpcode::kSelect: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kTopK: case HloOpcode::kSort: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kSubtract: case HloOpcode::kStochasticConvert: case HloOpcode::kTan: case HloOpcode::kTanh: case HloOpcode::kWhile: case HloOpcode::kXor: { // For these opcodes the output sharding can be determined by any operand // so we find the operand with the most specific sharding. const HloInstruction* best_operand = nullptr; for (const HloInstruction* operand : instruction->operands()) { if (operand->has_sharding() && (best_operand == nullptr || hlo_sharding_util::IsShardingMoreSpecific( operand->sharding(), best_operand->sharding()))) { best_operand = operand; } } return best_operand; } case HloOpcode::kCustomCall: { if (IsPassthroughCustomOps(instruction)) { return instruction->operand(0); } return nullptr; } // There is no suitable operand for the rest of the opcodes. case HloOpcode::kAddDependency: case HloOpcode::kAfterAll: case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: case HloOpcode::kAllGatherStart: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduceStart: case HloOpcode::kAllReduceDone: case HloOpcode::kBatchNormGrad: case HloOpcode::kBatchNormInference: case HloOpcode::kBatchNormTraining: case HloOpcode::kBitcast: case HloOpcode::kBroadcast: case HloOpcode::kCall: case HloOpcode::kCholesky: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCollectivePermuteStart: case HloOpcode::kConditional: case HloOpcode::kConstant: case HloOpcode::kConvolution: case HloOpcode::kCopyDone: case HloOpcode::kCopyStart: case HloOpcode::kDomain: case HloOpcode::kDot: case HloOpcode::kDynamicSlice: case HloOpcode::kDynamicUpdateSlice: case HloOpcode::kDynamicReshape: case HloOpcode::kFft: case HloOpcode::kFusion: case HloOpcode::kGather: case HloOpcode::kGetTupleElement: case HloOpcode::kInfeed: case HloOpcode::kIota: case HloOpcode::kOutfeed: case HloOpcode::kParameter: case HloOpcode::kPartitionId: case HloOpcode::kRecv: case HloOpcode::kRecvDone: case HloOpcode::kReduce: case HloOpcode::kReduceWindow: case HloOpcode::kReplicaId: case HloOpcode::kReshape: case HloOpcode::kRng: case HloOpcode::kRngGetAndUpdateState: case HloOpcode::kRngBitGenerator: case HloOpcode::kScatter: case HloOpcode::kSelectAndScatter: case HloOpcode::kSend: case HloOpcode::kSendDone: case HloOpcode::kTranspose: case HloOpcode::kTriangularSolve: case HloOpcode::kTuple: case HloOpcode::kGetDimensionSize: case HloOpcode::kSetDimensionSize: return nullptr; } } bool SupportSpatialPartitioning( const HloInstruction* instruction, const ShardingPropagation::ComputationMap& computation_map, bool is_spmd, bool allow_spmd_sharding_propagation_to_output, bool allow_spmd_sharding_propagation_to_parameters, const CustomCallShardingHelper* sharding_helper) { const bool is_entry_root = instruction->parent() ->parent() ->entry_computation() ->root_instruction() == instruction; if (instruction->parent()->root_instruction() == instruction && computation_map.find(instruction->parent()) == computation_map.end() && !(is_entry_root && allow_spmd_sharding_propagation_to_output)) { // We don't support sharding the root instruction of a computation yet, // unless the computation is a while body. return false; } if (instruction->IsElementwise() && (instruction->opcode() != HloOpcode::kRng || is_spmd)) { return true; } switch (instruction->opcode()) { case HloOpcode::kBroadcast: case HloOpcode::kConcatenate: case HloOpcode::kConditional: case HloOpcode::kConstant: case HloOpcode::kConvolution: case HloOpcode::kOptimizationBarrier: case HloOpcode::kDot: case HloOpcode::kDynamicSlice: case HloOpcode::kDynamicUpdateSlice: case HloOpcode::kGather: case HloOpcode::kGetTupleElement: case HloOpcode::kInfeed: case HloOpcode::kIota: case HloOpcode::kPad: case HloOpcode::kReduceWindow: case HloOpcode::kReshape: case HloOpcode::kScatter: case HloOpcode::kSelectAndScatter: case HloOpcode::kSlice: case HloOpcode::kSort: case HloOpcode::kTranspose: case HloOpcode::kTuple: case HloOpcode::kWhile: case HloOpcode::kReduce: case HloOpcode::kRngBitGenerator: case HloOpcode::kAllReduce: case HloOpcode::kReduceScatter: return true; case HloOpcode::kParameter: return allow_spmd_sharding_propagation_to_parameters || computation_map.find(instruction->parent()) != computation_map.end(); case HloOpcode::kReverse: return is_spmd; case HloOpcode::kCustomCall: if (!is_spmd) { return false; } if (auto* partitioner = GetCustomCallPartitioner(instruction->custom_call_target())) { return partitioner->IsCustomCallShardable(instruction); } return (IsPassthroughCustomOps(instruction) || sharding_helper->IsCustomCallShardable(instruction)); default: return false; } } std::optional<HloSharding> LookaheadUserSharding(HloInstruction* instr, bool is_spmd, const CallGraph& call_graph) { if (instr->user_count() != 1) { return std::nullopt; } HloInstruction* current_user = instr->users()[0]; std::optional<HloSharding> sharding; std::vector<HloInstruction*> users_chain = {instr, current_user}; // Collect single user instructions along the way. while (!current_user->has_sharding()) { // Only consider single user chains. if (current_user->users().size() != 1) { users_chain.clear(); break; } current_user = current_user->users()[0]; users_chain.push_back(current_user); } // Early exit for unsupported cases. if (users_chain.empty()) { return std::nullopt; } for (int i = users_chain.size() - 1; i >= 1; --i) { HloInstruction* user = users_chain[i]; HloInstruction* current = users_chain[i - 1]; CHECK(user->has_sharding()); sharding = ShardingPropagation::GetShardingFromUser( *current, *user, INT64_MAX, is_spmd, call_graph, /*sharding_helper=*/nullptr); // We need to set the sharding to the instruction, because // GetShardingFromUser() interface uses sharding from the instruction // itself. It will be cleared out later. if (sharding.has_value() && i != 1) { current->set_sharding(*sharding); continue; } break; } // Clear the sharding of the middle instructions we set the sharding of // because they were unsharded. for (int i = 1; i < users_chain.size() - 1; ++i) { users_chain[i]->clear_sharding(); } return sharding; } bool InferGatherParallelShardingFromOperands( HloInstruction* instruction, const hlo_sharding_util::GatherScatterParallelDims& parallel_dims, bool may_combine_partial_sharding) { CHECK(DynCast<HloGatherInstruction>(instruction)); bool changed = false; auto aligned_operand_parallel_dims = hlo_sharding_util::IndexAlignedOperandParallelDims(parallel_dims); auto output_parallel_dims = hlo_sharding_util::GetGatherParallelOutputDims( *instruction, parallel_dims); // Infer output sharding from scatter operand sharding. if (hlo_sharding_util::IsSpatiallyPartitioned(instruction->operand(0))) { changed |= MaybeImproveInstructionSharding( hlo_sharding_util:: InferGatherScatterParallelShardingFromOperandSharding( instruction->operand(0)->sharding(), instruction->operand(0)->shape(), instruction->shape(), absl::MakeConstSpan(aligned_operand_parallel_dims), absl::MakeConstSpan(output_parallel_dims)), instruction, may_combine_partial_sharding); } // Infer output sharding from scatter indices sharding. if (hlo_sharding_util::IsSpatiallyPartitioned(instruction->operand(1))) { changed |= MaybeImproveInstructionSharding( hlo_sharding_util:: InferGatherScatterParallelShardingFromOperandSharding( instruction->operand(1)->sharding(), instruction->operand(1)->shape(), instruction->shape(), absl::MakeConstSpan(parallel_dims.indices_parallel_dims), absl::MakeConstSpan(output_parallel_dims)), instruction, may_combine_partial_sharding); } return changed; } bool InferScatterParallelShardingFromOperands( HloInstruction* instruction, const hlo_sharding_util::GatherScatterParallelDims& parallel_dims, bool may_combine_partial_sharding) { HloScatterInstruction* scatter = DynCast<HloScatterInstruction>(instruction); CHECK(scatter); const int64_t operand_count = scatter->scatter_operand_count(); auto scatter_operands = scatter->scatter_operands(); auto scatter_indices = scatter->scatter_indices(); auto scatter_updates = scatter->scatter_updates(); bool changed = false; auto aligned_operand_parallel_dims = hlo_sharding_util::IndexAlignedOperandParallelDims(parallel_dims); auto update_parallel_dims = hlo_sharding_util::GetScatterParallelUpdateDims( *instruction, parallel_dims); auto output_parallel_dims = aligned_operand_parallel_dims; // Infer output sharding from scatter operand sharding. Shape shape = operand_count == 1 ? instruction->shape() : ShapeUtil::GetSubshape(instruction->shape(), {0}); for (int64_t i = 0; i != operand_count; ++i) { if (hlo_sharding_util::IsSpatiallyPartitioned(scatter_operands[i])) { changed |= MaybeImproveInstructionSubSharding( hlo_sharding_util:: InferGatherScatterParallelShardingFromOperandSharding( scatter_operands[i]->sharding(), scatter_operands[i]->shape(), shape, absl::MakeConstSpan(aligned_operand_parallel_dims), absl::MakeConstSpan(output_parallel_dims)), instruction, {i}, may_combine_partial_sharding); } } // Infer output sharding from scatter indices sharding. if (hlo_sharding_util::IsSpatiallyPartitioned(scatter_indices)) { auto parallel_sharding_from_indices = hlo_sharding_util:: InferGatherScatterParallelShardingFromOperandSharding( scatter_indices->sharding(), scatter_indices->shape(), shape, absl::MakeConstSpan(parallel_dims.indices_parallel_dims), absl::MakeConstSpan(output_parallel_dims)); for (int64_t i = 0; i != operand_count; ++i) { changed |= MaybeImproveInstructionSubSharding( parallel_sharding_from_indices, instruction, {i}, may_combine_partial_sharding); } } // Infer output sharding from scatter update sharding. for (int64_t i = 0; i != operand_count; ++i) { if (hlo_sharding_util::IsSpatiallyPartitioned(scatter_updates[i])) { changed |= MaybeImproveInstructionSubSharding( hlo_sharding_util:: InferGatherScatterParallelShardingFromOperandSharding( scatter_updates[i]->sharding(), scatter_updates[i]->shape(), shape, absl::MakeConstSpan(update_parallel_dims), absl::MakeConstSpan(output_parallel_dims)), instruction, {i}, may_combine_partial_sharding); } } return changed; } bool CanPropagateThroughAtAggressiveLevel(const HloInstruction& inst, int64_t aggressiveness) { // At minimum aggressiveness, only allow pass-through ops. if (aggressiveness < 1 && !(inst.IsElementwise() || inst.IsCustomCall("Sharding")) && inst.opcode() != HloOpcode::kTranspose && inst.opcode() != HloOpcode::kReshape && inst.opcode() != HloOpcode::kTuple && inst.opcode() != HloOpcode::kGetTupleElement && inst.opcode() != HloOpcode::kWhile && inst.opcode() != HloOpcode::kDynamicSlice && inst.opcode() != HloOpcode::kDynamicUpdateSlice && inst.opcode() != HloOpcode::kOptimizationBarrier && inst.opcode() != HloOpcode::kConcatenate && inst.opcode() != HloOpcode::kCall && inst.opcode() != HloOpcode::kCopy) { return false; } // Broadcast propagation should have at least aggressiveness 2. if (aggressiveness < 2 && inst.opcode() == HloOpcode::kBroadcast) { return false; } return true; } bool SameShardingMetadata(const HloSharding& a, const HloSharding& b) { DCHECK_EQ(a, b); auto same_metadata = [](absl::Span<const OpMetadata> a, absl::Span<const OpMetadata> b) { if (a.size() != b.size()) return false; for (int i = 0, e = a.size(); i < e; ++i) { if (!protobuf_util::ProtobufEquals(a[i], b[i])) { return false; } } return true; }; if (a.IsTuple()) { for (int i = 0, e = a.tuple_elements().size(); i < e; ++i) { if (!same_metadata(a.tuple_elements()[i].metadata(), b.tuple_elements()[i].metadata())) { return false; } } return true; } else { return same_metadata(a.metadata(), b.metadata()); } } auto same_metadata = [](absl::Span<const OpMetadata> a, absl::Span<const OpMetadata> b) { if (a.size() != b.size()) return false; for (int i = 0, e = a.size(); i < e; ++i) { if (!protobuf_util::ProtobufEquals(a[i], b[i])) { return false; } } return true; }; bool AssignShardingMetadata( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { bool changed = false; for (HloComputation* computation : module->computations(execution_threads)) { for (HloInstruction* instruction : computation->instructions()) { const auto& metadata = instruction->metadata(); if (!instruction->has_sharding() || metadata.ByteSizeLong() == 0) { continue; } HloSharding sharding_with_metadata = instruction->sharding().WithMetadata({metadata}, /*overwrite=*/false); if (!SameShardingMetadata(instruction->sharding(), sharding_with_metadata)) { instruction->set_sharding(std::move(sharding_with_metadata)); changed = true; } } } return changed; } bool RemoveShardingMetadata( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { bool changed = false; for (HloComputation* computation : module->computations(execution_threads)) { for (HloInstruction* instruction : computation->instructions()) { if (!instruction->has_sharding()) { continue; } HloSharding sharding_no_metadata = instruction->sharding().WithoutMetadata(); if (!SameShardingMetadata(instruction->sharding(), sharding_no_metadata)) { instruction->set_sharding(std::move(sharding_no_metadata)); changed = true; } } } return changed; } absl::Status CheckAndUpdateDeviceAssignmentsInWhileBody( HloInstruction* while_instruction) { auto bad_status = [](HloInstruction* instruction, int64_t device, HloInstruction* channel_instruction, int64_t correct_device) { return FailedPrecondition( "Instruction: %s is on device: %d, which conflicts with device: %d " "of channel instruction: %s", instruction->name(), device, correct_device, channel_instruction->name()); }; CHECK_EQ(while_instruction->opcode(), HloOpcode::kWhile); HloComputation* while_body = while_instruction->while_body(); // Maps a device number to an instruction in the while_body with that // device assignment. std::map<int64_t, HloInstruction*> devices_to_instructions; std::optional<int64_t> unique_device = std::nullopt; HloInstruction* channel_instruction = nullptr; for (HloInstruction* instruction : while_body->instructions()) { if (instruction->sharding_unique_device()) { auto opcode = instruction->opcode(); int64_t device = *instruction->sharding_unique_device(); if (unique_device.has_value()) { if (*unique_device != device) { return bad_status(instruction, device, channel_instruction, *unique_device); } } else if (((opcode == HloOpcode::kSend || opcode == HloOpcode::kRecv) && !Cast<HloSendRecvInstruction>(instruction) ->is_host_transfer()) // Cross-replica AllReduces don't have a channel_id, and we // don't enforce any invariant about their device assignment. || ((opcode == HloOpcode::kAllReduce || opcode == HloOpcode::kReduceScatter) && instruction->channel_id())) { channel_instruction = instruction; unique_device = device; if (!devices_to_instructions.empty()) { for (auto it = devices_to_instructions.begin(); it != devices_to_instructions.end(); ++it) { if (*unique_device != it->first) { return bad_status(it->second, it->first, channel_instruction, *unique_device); } } } } else { devices_to_instructions[device] = instruction; } } } if (unique_device.has_value()) { auto while_device = while_instruction->sharding_unique_device(); if (while_device.has_value() && *unique_device != *while_device) { return bad_status(while_instruction, *while_device, channel_instruction, *unique_device); } auto body_root = while_body->root_instruction(); auto root_device = body_root->sharding_unique_device(); if (!root_device.has_value()) { body_root->set_device_sharding(*unique_device); } else if (*unique_device != *root_device) { return bad_status(body_root, *root_device, channel_instruction, *unique_device); } } return absl::OkStatus(); } auto bad_status = [](HloInstruction* instruction, int64_t device, HloInstruction* channel_instruction, int64_t correct_device) { return FailedPrecondition( "Instruction: %s is on device: %d, which conflicts with device: %d " "of channel instruction: %s", instruction->name(), device, correct_device, channel_instruction->name()); }; bool RefineManualAutoShardingFromAuto( const HloSharding& to_merge, absl::Span<const int64_t> unspecified_dims, HloSharding* auto_sharding, HloSharding* manual_sharding) { if (!manual_sharding->IsManualSubgroup() || auto_sharding->IsManualSubgroup() || !manual_sharding->HasPartialReplication() || manual_sharding->subgroup_types().size() != 2) { // We do not support nested subgroup manual. man_conversion_op must have // replication in order to be merged. return false; } HloSharding partial_rep = hlo_sharding_util::PartiallyReplicateTiledShardingOnAllDimsExcept( to_merge, unspecified_dims); if (partial_rep.IsTileMaximal()) { return false; } // Merge with the non-manual partial annotation. if (!hlo_sharding_util::MergeShardingIfCompatible( partial_rep, auto_sharding->NumTiles() + 1, auto_sharding)) { return false; } // Merge with the manual partial annotation. const int64_t data_rank = partial_rep.TiledDataRank(); // We are also merging the non-manual sharding into the manual sharding. To // leverage existing merging implementation, we treat the manual dim as a // data dim, and add it right before the replication dim. std::vector<int64_t> partial_manual_shape( partial_rep.tile_assignment().dimensions().begin(), partial_rep.tile_assignment().dimensions().end()); partial_manual_shape.insert(partial_manual_shape.begin() + data_rank, 1); auto partial_tiling_for_manual = partial_rep.tile_assignment().Reshape(partial_manual_shape); HloSharding partial_rep_for_manual = HloSharding::PartialTile( partial_tiling_for_manual, partial_rep.metadata()); auto man_tiling = manual_sharding->tile_assignment(); if (manual_sharding->subgroup_types().back() != OpSharding::REPLICATED) { // Move the manual dim before replication dim. std::vector<int> transposed_dims(man_tiling.num_dimensions()); absl::c_iota(transposed_dims, 0); std::swap(transposed_dims.back(), transposed_dims[data_rank]); man_tiling = man_tiling.Transpose(transposed_dims); } HloSharding tmp_sharding_for_merging = HloSharding::PartialTile( std::move(man_tiling), manual_sharding->metadata()); if (!hlo_sharding_util::MergeShardingIfCompatible( partial_rep_for_manual, tmp_sharding_for_merging.NumTiles() + 1, &tmp_sharding_for_merging)) { return false; } std::vector<OpSharding::Type> subgroup_types; subgroup_types.push_back(OpSharding::MANUAL); if (tmp_sharding_for_merging.HasPartialReplication()) { subgroup_types.push_back(OpSharding::REPLICATED); } *manual_sharding = HloSharding::Subgroup( tmp_sharding_for_merging.tile_assignment(), subgroup_types, tmp_sharding_for_merging.metadata()); return true; } bool RefineManualAutoShardingFromManual( const HloSharding& to_merge, absl::Span<const int64_t> unspecified_dims, HloSharding* auto_sharding, HloSharding* manual_sharding) { if (!to_merge.IsManualSubgroup() || !manual_sharding->IsManualSubgroup() || !manual_sharding->HasPartialReplication() || auto_sharding->IsManualSubgroup() || manual_sharding->subgroup_types().size() != 2) { return false; } HloSharding partial_rep = hlo_sharding_util::PartiallyReplicateTiledShardingOnAllDimsExcept( to_merge, unspecified_dims); if (partial_rep.IsTileMaximal()) { return false; } if (!hlo_sharding_util::MergeShardingIfCompatible( partial_rep, manual_sharding->NumTiles() + 1, manual_sharding)) { return false; } HloSharding partial_rep_for_auto = HloSharding::Subgroup( partial_rep.tile_assignment(), std::vector<OpSharding::Type>(partial_rep.subgroup_types().size(), OpSharding::REPLICATED), partial_rep.metadata()); if (!hlo_sharding_util::MergeShardingIfCompatible( partial_rep_for_auto, auto_sharding->NumTiles() + 1, auto_sharding)) { return false; } return true; } bool InferUnspecifiedDimsFromOperand(HloInstruction* annotate_op, absl::Span<const int64_t> unspecified_dims, HloInstruction** man_conversion_op_after) { // ProcessShardingInstruction will either keep the "Sharding" custom call as // is or replace it with a copy. CHECK(annotate_op->IsCustomCall("Sharding") || annotate_op->opcode() == HloOpcode::kCopy); if (!hlo_sharding_util::IsSpatiallyPartitioned(annotate_op->operand(0))) { return false; } const HloSharding& operand_sharding = annotate_op->operand(0)->sharding(); if (!operand_sharding.IsTiled()) { return false; } HloInstruction* man_conversion_op = nullptr; if (annotate_op->user_count() == 1) { HloInstruction* user = annotate_op->users()[0]; if (user->IsCustomCall("SPMDFullToShardShape") || user->IsCustomCall("SPMDShardToFullShape")) { std::vector<int64_t> user_unspec_dims; if (!sharding_op_util::ParseAttributes( Cast<HloCustomCallInstruction>(user)->opaque(), &user_unspec_dims) .ok()) { return false; } absl::c_sort(user_unspec_dims); if (unspecified_dims != user_unspec_dims) { // The manual/auto conversion op must have the same set of unspecified // dims. return false; } man_conversion_op = user; } } *man_conversion_op_after = man_conversion_op; if (man_conversion_op == nullptr) { HloSharding partial_replicated = hlo_sharding_util::PartiallyReplicateTiledShardingOnAllDimsExcept( operand_sharding, unspecified_dims); HloSharding sharding = annotate_op->sharding(); if (!hlo_sharding_util::MergeShardingIfCompatible( partial_replicated, sharding.NumTiles() + 1, &sharding)) { return false; } annotate_op->set_sharding(sharding); return true; } if (man_conversion_op->IsCustomCall("SPMDFullToShardShape")) { HloSharding auto_sharding = annotate_op->sharding(); HloSharding manual_sharding = man_conversion_op->sharding(); if (!RefineManualAutoShardingFromAuto(operand_sharding, unspecified_dims, &auto_sharding, &manual_sharding)) { return false; } annotate_op->set_sharding(auto_sharding); man_conversion_op->set_sharding(manual_sharding); return true; } CHECK(man_conversion_op->IsCustomCall("SPMDShardToFullShape")); HloSharding manual_sharding = annotate_op->sharding(); HloSharding auto_sharding = man_conversion_op->sharding(); if (!RefineManualAutoShardingFromManual(operand_sharding, unspecified_dims, &auto_sharding, &manual_sharding)) { return false; } annotate_op->set_sharding(manual_sharding); man_conversion_op->set_sharding(auto_sharding); return true; } bool InferUnspecifiedDimsFromOneUser(HloInstruction* annotate_op, const HloInstruction* user, int64_t aggressiveness, bool is_spmd, absl::Span<const int64_t> unspecified_dims, HloInstruction* man_conversion_op, const CallGraph& call_graph) { CHECK(annotate_op->IsCustomCall("Sharding") || annotate_op->opcode() == HloOpcode::kCopy); if (!user->has_sharding() || !user->sharding().IsTiled()) { return false; } std::optional<HloSharding> user_sharding = ShardingPropagation::GetShardingFromUser( man_conversion_op == nullptr ? *annotate_op : *man_conversion_op, *user, aggressiveness, is_spmd, call_graph, /*sharding_helper=*/nullptr); if (!user_sharding.has_value() || user_sharding->IsTileMaximal()) { return false; } if (man_conversion_op == nullptr) { HloSharding partial_replicated = hlo_sharding_util::PartiallyReplicateTiledShardingOnAllDimsExcept( *user_sharding, unspecified_dims); HloSharding sharding = annotate_op->sharding(); if (!hlo_sharding_util::MergeShardingIfCompatible( partial_replicated, sharding.NumTiles() + 1, &sharding)) { return false; } annotate_op->set_sharding(sharding); return true; } if (man_conversion_op->IsCustomCall("SPMDFullToShardShape")) { HloSharding auto_sharding = annotate_op->sharding(); HloSharding manual_sharding = man_conversion_op->sharding(); if (!RefineManualAutoShardingFromManual(*user_sharding, unspecified_dims, &auto_sharding, &manual_sharding)) { return false; } annotate_op->set_sharding(auto_sharding); man_conversion_op->set_sharding(manual_sharding); return true; } CHECK(man_conversion_op->IsCustomCall("SPMDShardToFullShape")); HloSharding manual_sharding = annotate_op->sharding(); HloSharding auto_sharding = man_conversion_op->sharding(); if (!RefineManualAutoShardingFromAuto(*user_sharding, unspecified_dims, &auto_sharding, &manual_sharding)) { return false; } annotate_op->set_sharding(manual_sharding); man_conversion_op->set_sharding(auto_sharding); return true; } bool InferUnspecifiedDimsFromUsers(HloInstruction* annotate_op, absl::Span<const int64_t> unspecified_dims, int64_t aggressiveness, bool is_spmd, HloInstruction** man_conversion_op_after, const CallGraph& call_graph) { HloInstruction* man_conversion_op = nullptr; if (annotate_op->user_count() == 1) { HloInstruction* user = annotate_op->users()[0]; if (user->IsCustomCall("SPMDFullToShardShape") || user->IsCustomCall("SPMDShardToFullShape")) { std::vector<int64_t> user_unspec_dims; absl::c_sort(user_unspec_dims); if (!sharding_op_util::ParseAttributes( Cast<HloCustomCallInstruction>(user)->opaque(), &user_unspec_dims) .ok() || unspecified_dims != user_unspec_dims) { // The manual/auto conversion op must have the same set of unspecified // dims. return false; } man_conversion_op = user; } } *man_conversion_op_after = man_conversion_op; HloInstruction* op_for_users = man_conversion_op == nullptr ? annotate_op : man_conversion_op; bool changed = false; for (HloInstruction* user : op_for_users->users()) { changed |= InferUnspecifiedDimsFromOneUser( annotate_op, user, aggressiveness, is_spmd, unspecified_dims, man_conversion_op, call_graph); } return changed; } bool InferUnspecifiedDimsFromShardGroup( HloInstruction* annotate_op, absl::Span<const int64_t> unspecified_dims, const absl::flat_hash_set<HloInstruction*>& shard_group) { // ProcessShardingInstruction will either keep the "Sharding" custom call as // is or replace it with a copy. CHECK(annotate_op->IsCustomCall("Sharding") || annotate_op->opcode() == HloOpcode::kCopy); // Do not propagate sharding to ShardBarrierTo custom-call. if (annotate_op->IsCustomCall(spmd::kShardBarrierTo)) { return false; } bool changed = false; for (const HloInstruction* member : shard_group) { if (member == annotate_op) { continue; } // Do not propagate sharding from ShardBarrierFrom custom-call. if (member->IsCustomCall(spmd::kShardBarrierFrom)) { continue; } if (!hlo_sharding_util::IsSpatiallyPartitioned(member)) { continue; } const HloSharding& member_sharding = member->sharding(); if (!member_sharding.IsTiled()) { continue; } HloSharding partial_replicated = hlo_sharding_util::PartiallyReplicateTiledShardingOnAllDimsExcept( member_sharding, unspecified_dims); HloSharding sharding = annotate_op->sharding(); if (!hlo_sharding_util::MergeShardingIfCompatible( partial_replicated, sharding.NumTiles() + 1, &sharding)) { continue; } annotate_op->set_sharding(sharding); changed |= true; } return changed; } bool IsCSEPreventionTarget(const HloInstruction* instruction) { // Scalar broadcasts are the most common CSE target that causes cross-layer // propagation on unrelated subgraphs. return instruction->opcode() == HloOpcode::kBroadcast && instruction->operand(0)->shape().rank() == 0; } HloSharding SetCSEPreventionSharding(const HloSharding& sharding) { OpMetadata metadata; metadata.set_op_name("_sharding_propagation_cse_prevention"); return sharding.WithMetadata({metadata}, /*overwrite=*/true); } bool IsCSEPreventionSharding(const HloSharding& sharding) { if (sharding.metadata().size() != 1) { return false; } return sharding.metadata()[0].op_name() == "_sharding_propagation_cse_prevention"; } bool InferDotShardingFromOperands( HloInstruction* instruction, const CallGraph& call_graph, const dot_as_convolution_util::DotConvolutionDimsInfo& dnums, bool may_combine_partial_sharding, bool is_spmd) { auto from_operand = [&](int64_t operand_index) { auto operand = instruction->operand(operand_index); const HloSharding& operand_sharding = operand->sharding(); if (operand_sharding.IsTileMaximal()) { return operand_sharding; } std::vector<int64_t> contracting_dims; contracting_dims.reserve(dnums.contracting_dims.size()); for (const auto& dim : dnums.contracting_dims) { contracting_dims.push_back(operand_index == 0 ? dim.lhs : dim.rhs); } // It's possible that some size-1 spatial dims of convolutions are parsed as // non-contracting dims. We might have tiled dimensions on them. for (const auto& dim : operand_index == 0 ? dnums.rhs_non_contracting_dims : dnums.lhs_non_contracting_dims) { int64_t d = operand_index == 0 ? dim.lhs : dim.rhs; if (d >= 0) { contracting_dims.push_back(d); } } auto replicate_contracting_dims = hlo_sharding_util::PartiallyReplicateTiledShardingOnDims( operand_sharding, contracting_dims); std::vector<int64_t> out_dims_to_op_perm(instruction->shape().rank(), -1); std::vector<int64_t> op_dims_to_output_perm(operand->shape().rank(), -1); for (const auto& dim : dnums.batch_dims) { out_dims_to_op_perm[dim.output] = operand_index == 0 ? dim.lhs : dim.rhs; op_dims_to_output_perm[operand_index == 0 ? dim.lhs : dim.rhs] = dim.output; } for (const auto& dim : operand_index == 0 ? dnums.lhs_non_contracting_dims : dnums.rhs_non_contracting_dims) { out_dims_to_op_perm[dim.output] = operand_index == 0 ? dim.lhs : dim.rhs; op_dims_to_output_perm[operand_index == 0 ? dim.lhs : dim.rhs] = dim.output; } return *hlo_sharding_util::TransposeShardingWithCollapsedDims( replicate_contracting_dims, op_dims_to_output_perm, out_dims_to_op_perm); }; std::optional<HloSharding> improved_operand_0; std::optional<HloSharding> improved_operand_1; if (hlo_sharding_util::IsSpatiallyPartitioned(instruction->operand(0))) { improved_operand_0 = ReturnImprovedSharding( from_operand(0), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/false); } if (hlo_sharding_util::IsSpatiallyPartitioned(instruction->operand(1))) { improved_operand_1 = ReturnImprovedSharding( from_operand(1), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/false); } // If not improved sharding found then do not set any sharding. if (!improved_operand_0.has_value() && !improved_operand_1.has_value()) { return false; } // Sharding found from operand 0 but not operand 1. Set sharding from operand // 0 if (improved_operand_0.has_value() && !improved_operand_1.has_value()) { instruction->set_sharding(*improved_operand_0); return true; } // Sharding found from operand 1 but not operand 0. Set sharding from operand // 1 if (!improved_operand_0.has_value() && improved_operand_1.has_value()) { instruction->set_sharding(*improved_operand_1); return true; } CHECK(improved_operand_0.has_value() && improved_operand_1.has_value()); std::optional<HloSharding> lookahead_sharding = LookaheadUserSharding(instruction, is_spmd, call_graph); std::array<HloSharding, 2> sharding_priority = {*improved_operand_0, *improved_operand_1}; bool priority_defined_with_lookahead = false; // Found sharding from lookahead. if (lookahead_sharding.has_value()) { const bool operand_0_is_lookahead_subtiling = hlo_sharding_util::IsSubTilingOrEqualSharding( instruction->shape(), *lookahead_sharding, *improved_operand_0); const bool operand_1_is_lookahead_subtiling = hlo_sharding_util::IsSubTilingOrEqualSharding( instruction->shape(), *lookahead_sharding, *improved_operand_1); // If the sharding from operand 0 is a subtiling of the user, but not the // one from operand 1 prioritize that sharding. if (operand_0_is_lookahead_subtiling && !operand_1_is_lookahead_subtiling) { priority_defined_with_lookahead = true; } // If the sharding from operand 1 is a subtiling of the user, but not the // one from operand 0 prioritize that sharding. if (!operand_0_is_lookahead_subtiling && operand_1_is_lookahead_subtiling) { instruction->set_sharding(*improved_operand_1); std::swap(sharding_priority[0], sharding_priority[1]); priority_defined_with_lookahead = true; } } // If lookahead didn't define a priority then use size. if (!priority_defined_with_lookahead && ShapeUtil::ByteSizeOf(instruction->operand(0)->shape()) < ShapeUtil::ByteSizeOf(instruction->operand(1)->shape())) { std::swap(sharding_priority[0], sharding_priority[1]); } // Set primary sharding to the instruction and then try to improve it with // the secondary sharding. instruction->set_sharding(sharding_priority[0]); MaybeImproveInstructionSharding(sharding_priority[1], instruction, may_combine_partial_sharding); return true; } auto from_operand = [&](int64_t operand_index) { auto operand = instruction->operand(operand_index); const HloSharding& operand_sharding = operand->sharding(); if (operand_sharding.IsTileMaximal()) { return operand_sharding; } std::vector<int64_t> contracting_dims; contracting_dims.reserve(dnums.contracting_dims.size()); for (const auto& dim : dnums.contracting_dims) { contracting_dims.push_back(operand_index == 0 ? dim.lhs : dim.rhs); } // It's possible that some size-1 spatial dims of convolutions are parsed as // non-contracting dims. We might have tiled dimensions on them. for (const auto& dim : operand_index == 0 ? dnums.rhs_non_contracting_dims : dnums.lhs_non_contracting_dims) { int64_t d = operand_index == 0 ? dim.lhs : dim.rhs; if (d >= 0) { contracting_dims.push_back(d); } } auto replicate_contracting_dims = hlo_sharding_util::PartiallyReplicateTiledShardingOnDims( operand_sharding, contracting_dims); std::vector<int64_t> out_dims_to_op_perm(instruction->shape().rank(), -1); std::vector<int64_t> op_dims_to_output_perm(operand->shape().rank(), -1); for (const auto& dim : dnums.batch_dims) { out_dims_to_op_perm[dim.output] = operand_index == 0 ? dim.lhs : dim.rhs; op_dims_to_output_perm[operand_index == 0 ? dim.lhs : dim.rhs] = dim.output; } for (const auto& dim : operand_index == 0 ? dnums.lhs_non_contracting_dims : dnums.rhs_non_contracting_dims) { out_dims_to_op_perm[dim.output] = operand_index == 0 ? dim.lhs : dim.rhs; op_dims_to_output_perm[operand_index == 0 ? dim.lhs : dim.rhs] = dim.output; } return *hlo_sharding_util::TransposeShardingWithCollapsedDims( replicate_contracting_dims, op_dims_to_output_perm, out_dims_to_op_perm); }; bool InferConvolutionShardingFromOperands(HloInstruction* instruction, const CallGraph& call_graph, int64_t aggressiveness, bool may_combine_partial_sharding, bool is_spmd) { auto get_partitions_for_dims = [&](const HloInstruction* inst, absl::Span< const dot_as_convolution_util::DotConvolutionDimsInfo::DimNums> dims, int lhs_or_rhs) { int64_t partitions = 1; if (!inst->has_sharding()) { return partitions; } const auto& sharding = inst->sharding(); if (sharding.IsTileMaximal()) { return partitions; } for (const auto& dim : dims) { if (lhs_or_rhs == 0) { partitions *= sharding.tile_assignment().dim(dim.lhs); } else { CHECK_EQ(lhs_or_rhs, 1); partitions *= sharding.tile_assignment().dim(dim.rhs); } } return partitions; }; auto dot_dims = dot_as_convolution_util::ParseConvolutionDimsInfo(instruction); const int64_t lhs_conv_spatial_partitions = get_partitions_for_dims( instruction->operand(0), dot_dims.conv_spatial_dims, 0); const int64_t rhs_conv_spatial_partitions = get_partitions_for_dims( instruction->operand(1), dot_dims.conv_spatial_dims, 1); if (dot_dims.conv_spatial_dims.empty() || (lhs_conv_spatial_partitions == 1 && rhs_conv_spatial_partitions == 1 && instruction->batch_group_count() == 1 && instruction->feature_group_count() == 1)) { return InferDotShardingFromOperands(instruction, call_graph, dot_dims, may_combine_partial_sharding, is_spmd); } const auto& dnums = instruction->convolution_dimension_numbers(); const HloInstruction* lhs = instruction->operand(0); auto get_tiled_sharding_based_on_lhs = [&] { CHECK(!lhs->sharding().IsTileMaximal()); std::vector<int64_t> output_to_lhs_indices(instruction->shape().rank()); output_to_lhs_indices[dnums.output_batch_dimension()] = dnums.input_batch_dimension(); output_to_lhs_indices[dnums.output_feature_dimension()] = dnums.input_feature_dimension(); for (int64_t i = 0; i < dnums.input_spatial_dimensions_size(); ++i) { output_to_lhs_indices[dnums.output_spatial_dimensions(i)] = dnums.input_spatial_dimensions(i); } return hlo_sharding_util::TransposeSharding(lhs->sharding(), output_to_lhs_indices); }; if (!hlo_sharding_util::IsSpatiallyPartitioned(lhs)) { return false; } if (lhs->sharding().IsTileMaximal()) { return MaybeImproveInstructionSharding(lhs->sharding(), instruction, may_combine_partial_sharding); } if (IsConvolutionKernelSmall(instruction)) { // If the kernel is small compared to the input then we can generate an // output what is sharded the same way as the input. const auto& tile_assignment = lhs->sharding().tile_assignment(); if (tile_assignment.dim(dnums.input_feature_dimension()) > 1) { return false; } return MaybeImproveInstructionSharding(get_tiled_sharding_based_on_lhs(), instruction, may_combine_partial_sharding); } // If the kernel is large (e.g., backward convolution) then we only support // replicated output. We intend to keep the sharding along the batch dimension // between lhs and output. return MaybeImproveInstructionSharding( hlo_sharding_util::PartiallyReplicateTiledShardingOnAllDimsExcept( lhs->sharding(), {dnums.input_batch_dimension()}), instruction, may_combine_partial_sharding); } [&](const HloInstruction* inst, absl::Span< const dot_as_convolution_util::DotConvolutionDimsInfo::DimNums> dims, int lhs_or_rhs) { int64_t partitions = 1; if (!inst->has_sharding()) { return partitions; } const auto& sharding = inst->sharding(); if (sharding.IsTileMaximal()) { return partitions; } for (const auto& dim : dims) { if (lhs_or_rhs == 0) { partitions *= sharding.tile_assignment().dim(dim.lhs); } else { CHECK_EQ(lhs_or_rhs, 1); partitions *= sharding.tile_assignment().dim(dim.rhs); } } return partitions; }; auto get_tiled_sharding_based_on_lhs = [&] { CHECK(!lhs->sharding().IsTileMaximal()); std::vector<int64_t> output_to_lhs_indices(instruction->shape().rank()); output_to_lhs_indices[dnums.output_batch_dimension()] = dnums.input_batch_dimension(); output_to_lhs_indices[dnums.output_feature_dimension()] = dnums.input_feature_dimension(); for (int64_t i = 0; i < dnums.input_spatial_dimensions_size(); ++i) { output_to_lhs_indices[dnums.output_spatial_dimensions(i)] = dnums.input_spatial_dimensions(i); } return hlo_sharding_util::TransposeSharding(lhs->sharding(), output_to_lhs_indices); }; std::optional<HloSharding> InferBroadcastOperandSharding( const HloInstruction& instruction, bool is_spmd) { if (instruction.sharding().IsReplicated() || instruction.sharding().IsManual()) { return instruction.sharding(); } std::vector<int64_t> dims_to_replicate; bool needs_replication = false; for (int64_t i = 0; i < instruction.shape().rank(); ++i) { if (absl::c_count(instruction.dimensions(), i) == 0) { dims_to_replicate.push_back(i); if (instruction.sharding().tile_assignment().dim(i) > 1) { needs_replication = true; } } } // If not SPMD, only support when none of the partitioned dimensions in // the broadcast output belong to new dimensions. if (!is_spmd && needs_replication) { return std::nullopt; } return hlo_sharding_util::RemoveShapeDimensions( hlo_sharding_util::PartiallyReplicateTiledShardingOnDims( instruction.sharding(), dims_to_replicate), dims_to_replicate); } bool InferReduceShardingFromOperand(HloInstruction* instruction, bool may_combine_partial_sharding, bool is_spmd) { auto get_maybe_tuple_sharding = [&](HloSharding sharding) { if (instruction->shape().IsArray()) { return sharding; } std::vector<HloSharding> tuple(instruction->shape().tuple_shapes_size(), std::move(sharding)); return HloSharding::Tuple(instruction->shape(), tuple); }; auto* reduce = Cast<HloReduceInstruction>(instruction); bool changed = false; for (HloInstruction* operand : reduce->inputs()) { if (!hlo_sharding_util::IsSpatiallyPartitioned(operand)) { continue; } if (operand->sharding().IsReplicated() || (!is_spmd && absl::c_any_of(instruction->dimensions(), [operand](int64_t dim) { return operand->sharding().tile_assignment().dim(dim) > 1; }))) { // We are reducing along one of the sharded dimensions. We only // support this in SPMD. changed |= MaybeImproveInstructionSharding( get_maybe_tuple_sharding( hlo_sharding_util::ReplicateAllDataDims(operand->sharding())), reduce, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); continue; } auto after_partial_replication = operand->sharding().IsReplicated() ? operand->sharding() : hlo_sharding_util::PartiallyReplicateTiledShardingOnDims( operand->sharding(), reduce->dimensions()); if (after_partial_replication.IsReplicated()) { changed |= MaybeImproveInstructionSharding( get_maybe_tuple_sharding(after_partial_replication), reduce, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); continue; } // Use the same sharding for all tuple elements, because they are part // of the same reduce instruction. HloSharding new_sharding = get_maybe_tuple_sharding(hlo_sharding_util::RemoveShapeDimensions( after_partial_replication, reduce->dimensions())); changed |= MaybeImproveInstructionSharding( std::move(new_sharding), reduce, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(reduce) == 1); } return changed; } auto get_maybe_tuple_sharding = [&](HloSharding sharding) { if (instruction->shape().IsArray()) { return sharding; } std::vector<HloSharding> tuple(instruction->shape().tuple_shapes_size(), std::move(sharding)); return HloSharding::Tuple(instruction->shape(), tuple); }; absl::c_any_of(instruction->dimensions(), [operand](int64_t dim) { return operand->sharding().tile_assignment().dim(dim) > 1; }))) { absl::StatusOr<bool> ProcessShardingInstruction( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads, bool replace_sharding_with_copy, absl::flat_hash_map<const HloInstruction*, std::vector<int64_t>>* unspecified_dims, std::vector<HloSharding>* saved_root_shardings, absl::flat_hash_map<int64_t, HloSharding>* saved_parameter_shardings, absl::flat_hash_map<HloInstruction*, int64_t>* instruction_to_shard_group_id, absl::flat_hash_map<int64_t, absl::flat_hash_set<HloInstruction*>>* shard_group_id_to_shard_as_group, absl::flat_hash_map<int64_t, absl::flat_hash_set<HloInstruction*>>* shard_group_id_to_shard_like_group, const std::vector<bool>* allow_spmd_sharding_propagation_to_parameters_vector) { bool changed = false; const bool use_shard_group = instruction_to_shard_group_id && shard_group_id_to_shard_as_group && shard_group_id_to_shard_like_group; // Process shard group instruction and returns if current instruction needs // to be removed. auto process_shard_group_instruction = [&](HloInstruction* instruction, bool replaced_with_copy) -> absl::StatusOr<bool> { // Run shard group processing IFF it's not CSE prevention. if (replace_sharding_with_copy) { if (use_shard_group && instruction->has_sharding() && instruction->sharding().IsShardGroup()) { if (instruction->IsCustomCall("Sharding")) { CHECK(instruction->operand(0)->opcode() != HloOpcode::kParameter || (allow_spmd_sharding_propagation_to_parameters_vector && allow_spmd_sharding_propagation_to_parameters_vector->size() == module->entry_computation()->num_parameters() && allow_spmd_sharding_propagation_to_parameters_vector->at( instruction->operand(0)->parameter_number()))); } if (instruction->IsCustomCall("Sharding") && !replaced_with_copy) { // Pass shard group to operand sharding custom-call if it's not // replaced with a copy, meaning that the shardings are to annotate // shard_group. HloSharding operand_sharding = instruction->operand(0)->has_sharding() ? instruction->operand(0)->sharding() : HloSharding::Unknown(); operand_sharding.SetShardGroup( instruction->sharding().GetShardGroup()); instruction->mutable_operand(0)->set_sharding( std::move(operand_sharding)); return true; } else { // Otherwise store the shard group relations. const int64_t shard_group_id = instruction->sharding().GetShardGroup().shard_group_id; (*instruction_to_shard_group_id)[instruction] = shard_group_id; if (instruction->sharding().IsShardAs()) { auto& shard_as_group = (*shard_group_id_to_shard_as_group)[shard_group_id]; if (!shard_as_group.empty()) { CHECK(ShapeUtil::SameDimensions( instruction->shape(), (*shard_as_group.begin())->shape())) << "Instruction: " << instruction->ToString() << " has different shape from the shapes of the other " "instructions within the same shard_as group: " << (*shard_as_group.begin())->shape().ToString(); } shard_as_group.insert(instruction); } else { auto& shard_like_group = (*shard_group_id_to_shard_like_group)[shard_group_id]; if (!shard_like_group.empty()) { CHECK(ShapeUtil::SameDimensions( instruction->shape(), (*shard_like_group.begin())->shape())) << "Instruction: " << instruction->ToString() << " has different shape from the shapes of the other " "instructions within the same shard_like group: " << (*shard_like_group.begin())->shape().ToString(); } shard_like_group.insert(instruction); } HloSharding sharding = instruction->sharding(); sharding.ClearShardGroup(); instruction->set_sharding(std::move(sharding)); } } } return false; }; for (HloComputation* computation : module->computations(execution_threads)) { auto instructions = computation->MakeInstructionPostOrder(); for (auto it = instructions.rbegin(); it != instructions.rend(); ++it) { HloInstruction* instruction = *it; if (instruction->IsCustomCall("Sharding")) { HloSharding original_sharding = instruction->sharding(); TF_RET_CHECK(instruction->has_sharding()) << "Sharding instruction must have a sharding attribute"; VLOG(3) << "ProcessShardingInstruction: " << instruction->ToString(); std::vector<int64_t> unspec_dims; TF_RETURN_IF_ERROR(sharding_op_util::ParseAttributes( Cast<HloCustomCallInstruction>(instruction)->opaque(), &unspec_dims)); bool replaced_with_copy = replace_sharding_with_copy && (!original_sharding.IsUnknown() || instruction->operand(0)->opcode() == HloOpcode::kParameter); // Replace the sharding instruction with a copy node so that it does not // need special handling. if (replaced_with_copy) { auto copy = computation->AddInstruction(HloInstruction::CreateUnary( instruction->shape(), HloOpcode::kCopy, instruction->mutable_operand(0))); TF_ASSIGN_OR_RETURN( std::ignore, computation->ReplaceInstruction( instruction, copy, /*preserve_sharding=*/false, /*relay_control_dependency=*/false, /*remove_unused_operands=*/false)); copy->set_sharding(std::move(original_sharding)); instruction = copy; changed = true; } TF_ASSIGN_OR_RETURN( bool shard_group_remove_instruction, process_shard_group_instruction(instruction, replaced_with_copy)); if (!unspec_dims.empty()) { absl::c_sort(unspec_dims); unspecified_dims->emplace(instruction, std::move(unspec_dims)); } else if (!instruction->operand(0)->has_sharding()) { instruction->mutable_operand(0)->set_sharding( instruction->sharding()); } if (shard_group_remove_instruction) { TF_ASSIGN_OR_RETURN(std::ignore, computation->ReplaceInstruction( instruction, instruction->mutable_operand(0), /*preserve_sharding=*/false, /*relay_control_dependency=*/false, /*remove_unused_operands=*/false)); } } else { TF_ASSIGN_OR_RETURN(std::ignore, process_shard_group_instruction( instruction, /*replaced_with_copy=*/false)); } } } // Save the original shardings of parameters/outputs. HloInstruction* root_instr = module->entry_computation()->root_instruction(); if (saved_root_shardings != nullptr && root_instr->shape().IsTuple() && root_instr->has_sharding()) { saved_root_shardings->reserve( root_instr->sharding().tuple_elements().size()); for (const HloSharding& sharding : root_instr->sharding().tuple_elements()) { saved_root_shardings->push_back(sharding); } } if (saved_parameter_shardings != nullptr) { auto params = module->entry_computation()->parameter_instructions(); for (int64_t i = 0; i < params.size(); ++i) { if (params[i]->has_sharding()) { saved_parameter_shardings->insert({i, params[i]->sharding()}); } } } return changed; } [&](HloInstruction* instruction, bool replaced_with_copy) -> absl::StatusOr<bool> { // Run shard group processing IFF it's not CSE prevention. if (replace_sharding_with_copy) { if (use_shard_group && instruction->has_sharding() && instruction->sharding().IsShardGroup()) { if (instruction->IsCustomCall("Sharding")) { CHECK(instruction->operand(0)->opcode() != HloOpcode::kParameter || (allow_spmd_sharding_propagation_to_parameters_vector && allow_spmd_sharding_propagation_to_parameters_vector->size() == module->entry_computation()->num_parameters() && allow_spmd_sharding_propagation_to_parameters_vector->at( instruction->operand(0)->parameter_number()))); } if (instruction->IsCustomCall("Sharding") && !replaced_with_copy) { // Pass shard group to operand sharding custom-call if it's not // replaced with a copy, meaning that the shardings are to annotate // shard_group. HloSharding operand_sharding = instruction->operand(0)->has_sharding() ? instruction->operand(0)->sharding() : HloSharding::Unknown(); operand_sharding.SetShardGroup( instruction->sharding().GetShardGroup()); instruction->mutable_operand(0)->set_sharding( std::move(operand_sharding)); return true; } else { // Otherwise store the shard group relations. const int64_t shard_group_id = instruction->sharding().GetShardGroup().shard_group_id; (*instruction_to_shard_group_id)[instruction] = shard_group_id; if (instruction->sharding().IsShardAs()) { auto& shard_as_group = (*shard_group_id_to_shard_as_group)[shard_group_id]; if (!shard_as_group.empty()) { CHECK(ShapeUtil::SameDimensions( instruction->shape(), (*shard_as_group.begin())->shape())) << "Instruction: " << instruction->ToString() << " has different shape from the shapes of the other " "instructions within the same shard_as group: " << (*shard_as_group.begin())->shape().ToString(); } shard_as_group.insert(instruction); } else { auto& shard_like_group = (*shard_group_id_to_shard_like_group)[shard_group_id]; if (!shard_like_group.empty()) { CHECK(ShapeUtil::SameDimensions( instruction->shape(), (*shard_like_group.begin())->shape())) << "Instruction: " << instruction->ToString() << " has different shape from the shapes of the other " "instructions within the same shard_like group: " << (*shard_like_group.begin())->shape().ToString(); } shard_like_group.insert(instruction); } HloSharding sharding = instruction->sharding(); sharding.ClearShardGroup(); instruction->set_sharding(std::move(sharding)); } } } return false; }; VLOG(3) << "ProcessShardingInstruction: " << instruction->ToString(); int64_t ComputeNonRootUsers(const HloInstruction* instr) { int64_t non_root_users = instr->users().size(); for (int i = 0; i < instr->users().size(); ++i) { if (instr->users()[i] == instr->parent()->root_instruction()) { --non_root_users; } } return non_root_users; } /*static*/ absl::Status ShardingPropagation::NormalizeDomain( const DomainMetadata::Domain& domain, const DomainMetadata* metadata) { if (metadata != nullptr) { TF_ASSIGN_OR_RETURN(const auto& sharding_metadata, ShardingMetadata::ToShardingMetadata(metadata)); const auto& sharding = sharding_metadata->sharding(); if (sharding != nullptr) { bool is_spatially_partitioned = !sharding->HasUniqueDevice(); if (sharding->IsTuple()) { is_spatially_partitioned = absl::c_any_of( sharding->tuple_elements(), [](const HloSharding& s) { return !s.HasUniqueDevice(); }); } if (is_spatially_partitioned) { for (HloInstruction* d : domain.exit_domains) { HloInstruction* operand = d->mutable_operand(0); // Set sharding only if it is different. We don't overwrite the // metadata if it has the same sharding besides metadata. if (!operand->has_sharding() || operand->sharding() != *sharding) { HloSharding operand_sharding = *sharding; if (operand->shape().IsTuple() && !sharding->IsTuple()) { // Expand sharding into tuple sharding per // CloneShardingForDomain() in // third_party/tensorflow/compiler/xla/hlo/ir/hlo_sharding_metadata.cc operand_sharding = HloSharding::SingleTuple(operand->shape(), *sharding); } operand->set_sharding(std::move(operand_sharding)); } } return absl::OkStatus(); } } } return ShardingMetadata::NormalizeShardingDomain(domain, metadata); } std::optional<HloSharding> ShardingPropagation::GetShardingFromUser( const HloInstruction& instruction, const HloInstruction& user, int64_t aggressiveness, bool is_spmd, const CallGraph& call_graph, const CustomCallShardingHelper* sharding_helper) { if (!CanPropagateThroughAtAggressiveLevel(user, aggressiveness)) { return std::nullopt; } if (!hlo_sharding_util::IsSpatiallyPartitioned(&user)) { return std::nullopt; } const bool may_combine_partial_sharding = is_spmd && aggressiveness > 0; switch (user.opcode()) { case HloOpcode::kBroadcast: { return InferBroadcastOperandSharding(user, is_spmd); } case HloOpcode::kConcatenate: { if (aggressiveness == 0) { return std::nullopt; } if (user.sharding().IsReplicated()) { return user.sharding(); } const int64_t cdim = user.concatenate_dimension(); auto& tile_assignment = user.sharding().tile_assignment(); if (tile_assignment.dim(cdim) == 1) { // If we are concatenating along a non-sharded dimension then the // operands should have the same sharding as the result. return user.sharding(); } if (is_spmd) { // SPMD doesn't support tiling with part of the devices. Return the same // sharding. return user.sharding(); } // If we are concatenating along a sharded dimension then we want the // operands to be distributed among the devices their data is used. int64_t start_offset = 0; for (HloInstruction* op : user.operands()) { if (op == &instruction) { break; } start_offset += op->shape().dimensions(cdim); } const int64_t tile_shape = CeilOfRatio( user.shape().dimensions(cdim), tile_assignment.dimensions()[cdim]); std::vector<int64_t> start_indices(tile_assignment.num_dimensions()); std::vector<int64_t> end_indices(tile_assignment.dimensions().begin(), tile_assignment.dimensions().end()); start_indices[cdim] = start_offset / tile_shape; end_indices[cdim] = CeilOfRatio( start_offset + instruction.shape().dimensions(cdim), tile_shape); auto new_tile_assignment = tile_assignment.array().Slice(start_indices, end_indices); if (new_tile_assignment.num_elements() == 1) { return HloSharding::AssignDevice(*new_tile_assignment.begin(), user.sharding().metadata()); } return HloSharding::Tile(std::move(new_tile_assignment), user.sharding().metadata()); } case HloOpcode::kConvolution: { auto dot_dims = dot_as_convolution_util::ParseConvolutionDimsInfo(&user); if (dot_dims.conv_spatial_dims.empty()) { int64_t op_idx = user.operand_index(&instruction); return hlo_sharding_util::InferDotOperandSharding( &user, op_idx, dot_dims, /*consider_other_operand=*/true, may_combine_partial_sharding); } return std::nullopt; } case HloOpcode::kDynamicSlice: case HloOpcode::kDynamicUpdateSlice: { if (aggressiveness == 0) { return std::nullopt; } if (user.sharding().IsReplicated()) { return user.sharding(); } if (user.opcode() == HloOpcode::kDynamicUpdateSlice && &instruction == user.operand(0)) { return user.sharding(); } const HloInstruction* operand = user.opcode() == HloOpcode::kDynamicSlice ? user.operand(0) : user.operand(1); if (&instruction != operand) { return std::nullopt; } if (is_spmd) { return user.sharding(); } const auto& tile_assignment = user.sharding().tile_assignment(); for (int64_t i = 0; i < user.shape().rank(); ++i) { if (tile_assignment.dim(i) > 1 && user.shape().dimensions(i) != operand->shape().dimensions(i)) { return std::nullopt; } } return user.sharding(); } case HloOpcode::kReduceWindow: { auto* reduce_window = Cast<HloReduceWindowInstruction>(&user); if (!absl::c_linear_search(reduce_window->inputs(), &instruction)) { return std::nullopt; } if (reduce_window->shape().IsTuple()) { auto sub_sharding = reduce_window->sharding().GetSubSharding( reduce_window->shape(), {reduce_window->operand_index(&instruction)}); return sub_sharding; } return reduce_window->sharding(); } case HloOpcode::kReshape: { return hlo_sharding_util::PropagateShardingThroughReshape( user.shape(), instruction.shape(), user.sharding()); } case HloOpcode::kPad: { if (&instruction != user.operand(0)) { return std::nullopt; } return user.sharding(); } case HloOpcode::kSlice: { return user.sharding(); } case HloOpcode::kTranspose: { // Calculate the dimension numbers for reversing the current transpose // and then use TransposeSharding to convert the output sharding to an // input sharding. std::vector<int64_t> reverse_dimensions(user.dimensions().size()); for (int64_t i = 0; i < user.dimensions().size(); ++i) { reverse_dimensions[user.dimensions(i)] = i; } return hlo_sharding_util::TransposeSharding(user.sharding(), reverse_dimensions); } case HloOpcode::kTuple: { auto sub_sharding = user.sharding().GetSubSharding( user.shape(), {user.operand_index(&instruction)}); // In case the instruction is used as the operands multiple times within // this tuple, we will return the most specific sharding and propagate up. for (int64_t i = 0; i < user.shape().tuple_shapes_size(); ++i) { if (user.operand(i) == &instruction) { // Only evaluate GetSubSharding if this operand is of interest, // as it is relatively expensive. HloSharding alternative_sub_sharding = user.sharding().GetSubSharding(user.shape(), {i}); if (hlo_sharding_util::IsShardingMoreSpecific( alternative_sub_sharding, sub_sharding)) { sub_sharding = alternative_sub_sharding; } } } return sub_sharding; } case HloOpcode::kGetTupleElement: { int64_t sharding_index = 0; for (int i = 0; i < instruction.shape().tuple_shapes_size(); ++i) { if (i == user.tuple_index()) { break; } if (instruction.shape().tuple_shapes(i).IsArray()) { sharding_index += 1; } else { sharding_index += ShapeUtil::GetLeafCount(instruction.shape().tuple_shapes(i)); } } if (user.shape().IsArray()) { // Use ReplicateAllDataDims instead of HloSharding::Replicate() to // preserve manual subgroups. HloSharding new_sharding = instruction.has_sharding() ? instruction.sharding() : HloSharding::SingleTuple( instruction.shape(), hlo_sharding_util::ReplicateAllDataDims(user.sharding())); new_sharding.tuple_elements()[sharding_index] = user.sharding(); return new_sharding; } else { if (user.sharding().tuple_elements().empty()) { return std::nullopt; } HloSharding new_sharding = instruction.has_sharding() ? instruction.sharding() : HloSharding::SingleTuple( instruction.shape(), hlo_sharding_util::ReplicateAllDataDims( user.sharding().tuple_elements()[0])); for (int64_t i = 0; i < user.sharding().tuple_elements().size(); ++i) { new_sharding.tuple_elements()[sharding_index + i] = user.sharding().tuple_elements()[i]; } return new_sharding; } } case HloOpcode::kDot: { int64_t op_idx = user.operand_index(&instruction); auto dnums = dot_as_convolution_util::ParseDotGeneralFromDot(&user); return hlo_sharding_util::InferDotOperandSharding( &user, op_idx, dnums, /*consider_other_operand=*/true, may_combine_partial_sharding); } case HloOpcode::kReduce: { if (instruction.shape().rank() == 0) { return std::nullopt; } auto user_sharding = user.shape().IsTuple() ? user.sharding().GetSubSharding( user.shape(), {user.operand_index(&instruction)}) : user.sharding(); if (!user_sharding.IsTileMaximal()) { std::vector<int64_t> target_tile_assignment_dimensions( instruction.shape().rank() + (user_sharding.ReplicateOnLastTileDim() ? 1 : 0) + user_sharding.subgroup_types().size()); const auto& dimensions = user.dimensions(); int64_t next_output_dim = 0; for (int64_t i = 0; i < target_tile_assignment_dimensions.size(); ++i) { if (absl::c_find(dimensions, i) == dimensions.end()) { target_tile_assignment_dimensions[i] = user_sharding.tile_assignment().dim(next_output_dim++); } else { target_tile_assignment_dimensions[i] = 1; } } auto tile_assignment = user_sharding.tile_assignment().Reshape( target_tile_assignment_dimensions); user_sharding = user_sharding.ReplicateOnLastTileDim() ? HloSharding::PartialTile(tile_assignment, user_sharding.metadata()) : HloSharding::Subgroup(tile_assignment, user_sharding.subgroup_types(), user_sharding.metadata()); } // Try to merge with sharding from other operands if they can improve // current sharding. const auto* reduce = Cast<const HloReduceInstruction>(&user); for (const HloInstruction* operand : reduce->inputs()) { if (operand != &instruction && operand->has_sharding()) { hlo_sharding_util::MergeShardingIfCompatible( operand->sharding(), user_sharding.NumTiles() + 1, &user_sharding); } } return user_sharding; } case HloOpcode::kSort: { HloSharding user_sharding = user.sharding(); if (user_sharding.IsTuple()) { return user_sharding.GetSubSharding(user.shape(), {user.operand_index(&instruction)}); } return user_sharding; } case HloOpcode::kReverse: { return hlo_sharding_util::ReverseSharding(user.sharding(), user.dimensions()); } case HloOpcode::kOutfeed: { if (&instruction != user.operand(0)) { return std::nullopt; } std::vector<Shape> operand_shapes(user.operand_count()); for (int i = 0; i < user.operand_count(); ++i) { operand_shapes[i] = user.operand(i)->shape(); } return user.sharding().GetSubSharding( ShapeUtil::MakeTupleShape(operand_shapes), {0}); } case HloOpcode::kGather: { if (&instruction == user.operand(1)) { return hlo_sharding_util:: GatherIndexShardingFromOutputIndexPassthroughDimensions( user.sharding(), &user); } if (is_spmd) { return hlo_sharding_util::GatherOperandShardingFromOutput( user.sharding(), user, call_graph); } return std::nullopt; } case HloOpcode::kScatter: { auto& scatter_user = *Cast<HloScatterInstruction>(&user); const int64_t operand_count = scatter_user.scatter_operand_count(); auto scatter_operands = scatter_user.scatter_operands(); auto scatter_indices = scatter_user.scatter_indices(); auto scatter_updates = scatter_user.scatter_updates(); // Infer sharding for scatter operand. const int64_t operand_index = absl::c_find(scatter_operands, &instruction) - scatter_operands.cbegin(); if (operand_index < operand_count) { return user.sharding().IsTuple() ? user.sharding().GetSubSharding( user.shape(), {operand_index}) : user.sharding(); } // Infer sharding for scatter indices. if (&instruction == scatter_indices) { std::vector<const HloInstruction*> partitioned_updates; for (const HloInstruction* update : scatter_updates) { if (hlo_sharding_util::IsSpatiallyPartitioned(update)) { partitioned_updates.push_back(update); } } if (partitioned_updates.empty()) { return std::nullopt; } std::vector<HloSharding> shardings; absl::c_transform( partitioned_updates, std::back_inserter(shardings), [&scatter_user](const HloInstruction* update) { return hlo_sharding_util:: ScatterIndexShardingFromUpdateIndexPassthroughDimensions( update->sharding(), &scatter_user); }); return hlo_sharding_util::FindCommonSharding(shardings); } // Infer sharding for scatter update. const int64_t update_index = absl::c_find(scatter_updates, &instruction) - scatter_updates.cbegin(); CHECK_LE(update_index, operand_count); auto from_indices = hlo_sharding_util::IsSpatiallyPartitioned(scatter_indices) ? hlo_sharding_util:: ScatterUpdateShardingFromIndexIndexPassthroughDimensions( scatter_indices->sharding(), &scatter_user) : HloSharding::Replicate(); if (is_spmd) { auto from_output = hlo_sharding_util::ScatterUpdateShardingFromOutput( user.sharding().IsTuple() ? user.sharding().GetSubSharding(user.shape(), {update_index}) : user.sharding(), scatter_user, call_graph); if (from_output.has_value()) { // Use sharding from output as primary sharding since it prioritize // parallel sharding first as this is how it is in spmd_partitioner. hlo_sharding_util::MergeShardingIfCompatible( from_indices, from_output->NumTiles() + 1, &*from_output); if (!from_output->IsTileMaximal()) { return from_output; } } } if (!from_indices.IsTileMaximal()) { return from_indices; } return std::nullopt; } case HloOpcode::kCustomCall: { bool compatible_shapes = ShapeUtil::CompatibleIgnoringElementType( instruction.shape(), user.shape()); if (!compatible_shapes) { // Incompatible shapes, we will not propagate sharding. return std::nullopt; } if (!sharding_helper) { // No available sharding helper and shapes are compatible, we will // propagate sharding. return user.sharding(); } if (sharding_helper->CanPropagateShardingToOperands(&user)) { return user.sharding(); } return std::nullopt; } default: { // If the user output shape is compatible with the current instruction // shape excluding element type and the current instruction is supported // by spatial partitioning, then the user sharding can be used for // propagation to the current instruction. if (ShapeUtil::CompatibleIgnoringElementType(instruction.shape(), user.shape())) { return user.sharding(); } return std::nullopt; } } } [&scatter_user](const HloInstruction* update) { return hlo_sharding_util:: ScatterIndexShardingFromUpdateIndexPassthroughDimensions( update->sharding(), &scatter_user); }); bool AggressiveConcatOperandShardingCanPassThrough( const HloInstruction* concat_operand) { return ( hlo_sharding_util::IsSpatiallyPartitioned(concat_operand) && (concat_operand->has_sharding() && concat_operand->sharding().NumTiles() > 1) && concat_operand->opcode() == HloOpcode::kReshape && (concat_operand->operand(0)->opcode() == HloOpcode::kParameter || concat_operand->operand(0)->opcode() == HloOpcode::kGetTupleElement)); } bool InferDynamicSliceOrDynamicUpdateSliceShardingFromOperands( HloInstruction* instruction, int64_t aggressiveness, bool may_combine_partial_sharding) { const HloInstruction* operand = instruction->opcode() == HloOpcode::kDynamicSlice ? instruction->operand(0) : instruction->operand(1); auto slice_dim_is_sharded = [&]() { if (!hlo_sharding_util::IsSpatiallyPartitioned(operand) || operand->sharding().IsManual() || operand->sharding().NumTiles() == 1) { return false; } for (int64_t i = 0; i < instruction->shape().rank(); ++i) { const auto& tile_assignment = operand->sharding().tile_assignment(); if (tile_assignment.dim(i) > 1 && instruction->shape().dimensions(i) != operand->shape().dimensions(i)) { return true; } } return false; }; // Do not pass through sharding annotation at the first iteration // if slice dim is sharded. if (aggressiveness == 0 && slice_dim_is_sharded()) { return false; } auto propagate_slicing = [&]() { if (!hlo_sharding_util::IsSpatiallyPartitioned(operand)) { return false; } if (slice_dim_is_sharded()) { return false; } return MaybeImproveInstructionSharding( operand->sharding(), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); }; auto propagate_base = [&]() { if (instruction->opcode() != HloOpcode::kDynamicUpdateSlice) { return false; } if (!hlo_sharding_util::IsSpatiallyPartitioned(instruction->operand(0))) { return false; } return MaybeImproveInstructionSharding(instruction->operand(0)->sharding(), instruction, may_combine_partial_sharding); }; bool changed = propagate_slicing(); changed |= propagate_base(); return changed; } auto slice_dim_is_sharded = [&]() { if (!hlo_sharding_util::IsSpatiallyPartitioned(operand) || operand->sharding().IsManual() || operand->sharding().NumTiles() == 1) { return false; } for (int64_t i = 0; i < instruction->shape().rank(); ++i) { const auto& tile_assignment = operand->sharding().tile_assignment(); if (tile_assignment.dim(i) > 1 && instruction->shape().dimensions(i) != operand->shape().dimensions(i)) { return true; } } return false; }; auto propagate_slicing = [&]() { if (!hlo_sharding_util::IsSpatiallyPartitioned(operand)) { return false; } if (slice_dim_is_sharded()) { return false; } return MaybeImproveInstructionSharding( operand->sharding(), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); }; auto propagate_base = [&]() { if (instruction->opcode() != HloOpcode::kDynamicUpdateSlice) { return false; } if (!hlo_sharding_util::IsSpatiallyPartitioned(instruction->operand(0))) { return false; } return MaybeImproveInstructionSharding(instruction->operand(0)->sharding(), instruction, may_combine_partial_sharding); }; bool ShardingPropagation::InferShardingFromShardGroup( HloInstruction* instruction, const ComputationMap& computation_map, int64_t aggressiveness, const absl::flat_hash_set<HloInstruction*>& shard_group) { if (!CanPropagateThroughAtAggressiveLevel(*instruction, aggressiveness)) { return false; } // Do not change manual sharding. if (instruction->has_sharding() && instruction->sharding().IsManual()) { return false; } // Do not propagate sharding to ShardBarrierTo custom-call. if (instruction->IsCustomCall(spmd::kShardBarrierTo)) { return false; } // Propagate manual sharding. if (!instruction->has_sharding() || instruction->sharding().IsTileMaximal()) { for (const HloInstruction* member : shard_group) { if (!member->has_sharding() || !member->sharding().IsManual() || member == instruction) { continue; } instruction->set_sharding(member->sharding()); return true; } } const bool may_combine_partial_sharding = is_spmd_ && aggressiveness > 0; bool changed = false; for (const HloInstruction* member : shard_group) { // Do not propagate sharding from ShardBarrierFrom custom-call. if (member == instruction || member->IsCustomCall(spmd::kShardBarrierFrom)) { continue; } changed |= MaybeImproveInstructionSharding(member->sharding(), instruction, may_combine_partial_sharding); } return changed; } bool ShardingPropagation::InferShardingFromOperands( HloInstruction* instruction, const ComputationMap& computation_map, int64_t aggressiveness, const CallGraph& call_graph, const absl::flat_hash_set<absl::string_view>& execution_threads) { if (!CanPropagateThroughAtAggressiveLevel(*instruction, aggressiveness)) { return false; } // Do not change manual sharding. if (instruction->has_sharding() && instruction->sharding().IsManual()) { return false; } // Propagate manual sharding. Avoid tuple shaped HLOs that group independent // together. Reduce, ReduceWindow, and Sort can be tuples but the elements // are correlated, so we propagate manual sharding through them. // For custom-calls with manual operand, the default propagation logic will // just assign manual to the whole custom-call. const bool custom_call_condition = instruction->opcode() == HloOpcode::kCustomCall && instruction->shape().IsTuple(); // For asynchronous instructions with manual operand, we assign manual to the // whole instructions if the async_execution_thread is not in the // execution_threads. const bool async_instr_condition = instruction->IsAsynchronous() && !HloInstruction::IsThreadIncluded(instruction->async_execution_thread(), execution_threads); if ((!instruction->has_sharding() || instruction->sharding().IsTileMaximal()) && (instruction->shape().IsArray() || instruction->opcode() == HloOpcode::kReduce || instruction->opcode() == HloOpcode::kSort || instruction->opcode() == HloOpcode::kReduceWindow || custom_call_condition || async_instr_condition)) { for (const HloInstruction* op : instruction->operands()) { if (!op->has_sharding() || !op->sharding().IsManual()) continue; // Do not pass through manual sharding to SPMDShardToFullShape. if (instruction->IsCustomCall("SPMDShardToFullShape")) { return false; } // Do not pass through manual sharding to concat or dynamic slice when // aggressiveneess is 0. if (aggressiveness == 0 && (instruction->opcode() == HloOpcode::kConcatenate || instruction->opcode() == HloOpcode::kDynamicSlice)) { return false; } instruction->set_sharding( HloSharding::Manual(op->sharding().metadata()) .NormalizeTupleSharding(instruction->shape())); return true; } } const bool may_combine_partial_sharding = is_spmd_ && aggressiveness > 0; if (!SupportSpatialPartitioning( instruction, computation_map, is_spmd_, allow_spmd_sharding_propagation_to_output_, /*allow_spmd_sharding_propagation_to_parameters=*/false, sharding_helper_.get())) { // If an array shaped HLO doesn't support spatial partitioning but at least // one of its operand is replicated then we make the HLO replicated as well. if (instruction->shape().IsTuple() || instruction->operand_count() == 0 || instruction == instruction->parent()->root_instruction() || instruction->HasSideEffect()) { return false; } for (const HloInstruction* op : instruction->operands()) { if (op->has_sharding() && op->sharding().IsTileMaximal() && !op->sharding().HasUniqueDevice()) { return MaybeImproveInstructionSharding(op->sharding(), instruction, may_combine_partial_sharding); } } return false; } auto get_maybe_tuple_sharding = [&](HloSharding sharding) { if (instruction->shape().IsArray()) { return sharding; } std::vector<HloSharding> tuple(instruction->shape().tuple_shapes_size(), std::move(sharding)); return HloSharding::Tuple(instruction->shape(), tuple); }; switch (instruction->opcode()) { case HloOpcode::kGetTupleElement: { const HloInstruction* operand = instruction->operand(0); if (!hlo_sharding_util::IsSpatiallyPartitioned(operand)) { return false; } HloSharding new_sharding = operand->sharding().GetSubSharding( operand->shape(), {instruction->tuple_index()}); if (new_sharding.IsManual()) { instruction->set_sharding(std::move(new_sharding)); return true; } return MaybeImproveInstructionSharding( std::move(new_sharding), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); } case HloOpcode::kTuple: { if (absl::c_none_of( instruction->operands(), [](const HloInstruction* hlo) { return hlo_sharding_util::IsSpatiallyPartitioned(hlo); })) { // None of the operands have a spatially partitioned sharding. return false; } const Shape& shape = instruction->shape(); // Go through each operand and if the operand has a sharding that is // better than the current sharding for that tuple element then update // it. If the current sharding does not exist, assume its replicated. std::vector<HloSharding> sub_shardings; if (instruction->has_sharding()) { sub_shardings = instruction->sharding().tuple_elements(); } else { // If instruction does not have a sharding, assume its replicated to // allow refinement. sub_shardings.assign(HloSharding::RequiredLeaves(shape), HloSharding::Replicate()); } // This is required to allow manual sharding on operands to be propagated // to the tuple. hlo_sharding_util::IsShardingMoreSpecific() returns false // if any of the shardings involved is manual, so using it directly will // prevent manual sharding on an operand to be propagated to the tuple // when it has no existing sharding. auto is_more_specific = [instruction](const HloSharding& operand_sharding, const HloSharding& existing) { // If the instruction originally had no sharding, always prefer operand // sharding. return !instruction->has_sharding() || hlo_sharding_util::IsShardingMoreSpecific(operand_sharding, existing); }; int64_t sub_sharding_index = 0; for (int64_t i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const HloInstruction* operand = instruction->operand(i); if (operand->has_sharding()) { if (operand->shape().IsTuple()) { for (int64_t j = 0, e = ShapeUtil::GetLeafCount(operand->shape()); j < e; ++j) { if (is_more_specific(operand->sharding().tuple_elements()[j], sub_shardings[sub_sharding_index + j])) { sub_shardings[sub_sharding_index + j] = operand->sharding().tuple_elements()[j]; } } } else { std::optional<HloSharding> op_sharding = hlo_sharding_util::GetOutputSharding(operand); CHECK(op_sharding.has_value()) << "Expected sharding for " << operand->ToString(); if (is_more_specific(op_sharding.value(), sub_shardings[sub_sharding_index])) { sub_shardings[sub_sharding_index] = op_sharding.value(); } } } sub_sharding_index += ShapeUtil::GetLeafCount(operand->shape()); } HloSharding new_sharding = HloSharding::Tuple(shape, sub_shardings); if (!instruction->has_sharding() || new_sharding != instruction->sharding()) { instruction->set_sharding(std::move(new_sharding)); return true; } return false; } case HloOpcode::kReduce: { // Reduce could have a tuple shape, where the first half of operands are // the arrays to reduce, and the second half of operands are the init // values. return InferReduceShardingFromOperand( instruction, may_combine_partial_sharding, is_spmd_); } case HloOpcode::kBroadcast: { // Make forward propagation through broadcast low priority to avoid // resharding after broadcast. if (aggressiveness < 3) { return false; } const HloInstruction* op = instruction->operand(0); if (!hlo_sharding_util::IsSpatiallyPartitioned(op) || op->sharding().IsReplicated()) { return false; } // The output will be tiled along the broadcasted dimension the same way // as the input for the broadcast while the other dimensions are kept // non-tiled. std::vector<int64_t> target_tile_assignment_dimensions; const auto& dimensions = instruction->dimensions(); for (int64_t i = 0; i < instruction->shape().rank(); ++i) { auto it = absl::c_find(dimensions, i); if (it == dimensions.end()) { target_tile_assignment_dimensions.push_back(1); } else { const int64_t source_dim = std::distance(dimensions.begin(), it); target_tile_assignment_dimensions.push_back( op->sharding().tile_assignment().dim(source_dim)); } } for (int64_t i = op->sharding().TiledDataRank(); i < op->sharding().tile_assignment().num_dimensions(); ++i) { target_tile_assignment_dimensions.push_back( op->sharding().tile_assignment().dim(i)); } auto new_tile_assignment = op->sharding().tile_assignment().Reshape( target_tile_assignment_dimensions); HloSharding new_sharding = op->sharding().ReplicateOnLastTileDim() ? HloSharding::PartialTile(new_tile_assignment, op->sharding().metadata()) : HloSharding::Subgroup(new_tile_assignment, op->sharding().subgroup_types(), op->sharding().metadata()); return MaybeImproveInstructionSharding( std::move(new_sharding), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ComputeNonRootUsers(instruction) == 1); } case HloOpcode::kConcatenate: { const HloInstruction* operand = PickRepresentativeOperand(instruction); if (!operand || !hlo_sharding_util::IsSpatiallyPartitioned(operand)) { return false; } if (aggressiveness == 0) { for (const HloInstruction* concat_operand : instruction->operands()) { if (!AggressiveConcatOperandShardingCanPassThrough(concat_operand)) { return false; } const auto& tile_assignment = concat_operand->sharding().tile_assignment(); for (int64_t i = 0; i < instruction->shape().rank(); ++i) { if (absl::c_linear_search(instruction->dimensions(), i) && tile_assignment.dim(i) > 1) { return false; } } } } return MaybeImproveInstructionSharding( operand->sharding(), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ComputeNonRootUsers(instruction) == 1); } case HloOpcode::kConvolution: return InferConvolutionShardingFromOperands( instruction, call_graph, aggressiveness, may_combine_partial_sharding, is_spmd_); case HloOpcode::kTranspose: { const HloInstruction* input = instruction->operand(0); if (!hlo_sharding_util::IsSpatiallyPartitioned(input)) { return false; } HloSharding sharding = hlo_sharding_util::TransposeSharding( input->sharding(), instruction->dimensions()); return MaybeImproveInstructionSharding( std::move(sharding), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ComputeNonRootUsers(instruction) == 1); } case HloOpcode::kReduceWindow: { auto* reduce_window = Cast<HloReduceWindowInstruction>(instruction); auto has_dilation = [](const WindowDimension& dimensions) { return dimensions.base_dilation() > 1 || dimensions.window_dilation() > 1; }; if (absl::c_any_of(instruction->window().dimensions(), has_dilation)) { VLOG(2) << "Not applying sharding to reduce window because dilatation " "isn't supported yet: " << reduce_window->ToString(); return false; } bool changed = false; for (HloInstruction* operand : reduce_window->inputs()) { if (!hlo_sharding_util::IsSpatiallyPartitioned(operand)) { continue; } changed |= MaybeImproveInstructionSharding( get_maybe_tuple_sharding(operand->sharding()), reduce_window, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); } return changed; } case HloOpcode::kSelectAndScatter: { // Shard according to first operand, as output keeps the same shape. const HloInstruction* lhs = instruction->operand(0); if (!hlo_sharding_util::IsSpatiallyPartitioned(lhs)) { return false; } auto has_base_dilation = [](const WindowDimension& dimensions) { return dimensions.base_dilation() > 1; }; if (absl::c_any_of(instruction->window().dimensions(), has_base_dilation)) { VLOG(2) << "Not applying sharding to select-and-scatter because " "base dilation isn't supported yet: " << instruction->ToString(); return false; } return MaybeImproveInstructionSharding( lhs->sharding(), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ComputeNonRootUsers(instruction) == 1); } case HloOpcode::kReshape: { if (!hlo_sharding_util::IsSpatiallyPartitioned(instruction->operand(0))) { return false; } HloSharding new_sharding = hlo_sharding_util::PropagateShardingThroughReshape( instruction->operand(0)->shape(), instruction->shape(), instruction->operand(0)->sharding()); return MaybeImproveInstructionSharding( std::move(new_sharding), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); return false; } case HloOpcode::kReverse: { const HloInstruction* operand = instruction->operand(0); if (!hlo_sharding_util::IsSpatiallyPartitioned(operand)) { return false; } return MaybeImproveInstructionSharding( hlo_sharding_util::ReverseSharding(operand->sharding(), instruction->dimensions()), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ComputeNonRootUsers(instruction) == 1); } case HloOpcode::kDot: { const auto& dnums = dot_as_convolution_util::ParseDotGeneralFromDot(instruction); return InferDotShardingFromOperands(instruction, call_graph, dnums, may_combine_partial_sharding, is_spmd_); } case HloOpcode::kParameter: { auto parent_it = computation_map.find(instruction->parent()); if (parent_it == computation_map.end()) { return false; } const HloInstruction* parent = parent_it->second; switch (parent->opcode()) { case HloOpcode::kConditional: { for (int64_t i = 1; i < parent->operand_count(); ++i) { if (parent->called_computations()[i - 1] == instruction->parent()) { if (parent->operand(i)->has_sharding()) { return MaybeImproveInstructionSharding( parent->operand(i)->sharding(), instruction, may_combine_partial_sharding); } return false; } } return false; } case HloOpcode::kCall: { int64_t i = instruction->parameter_number(); if (parent->operand(i)->has_sharding()) { return MaybeImproveInstructionSharding( parent->operand(i)->sharding(), instruction, may_combine_partial_sharding); } return false; } default: return false; } } case HloOpcode::kSort: { const HloInstruction* operand = PickRepresentativeOperand(instruction); if (!operand || !hlo_sharding_util::IsSpatiallyPartitioned(operand)) { return false; } HloSortInstruction* sort = DynCast<HloSortInstruction>(instruction); CHECK(sort); const int64_t sort_dim = sort->sort_dimension(); if (!operand->sharding().IsTileMaximal() && operand->sharding().tile_assignment().dim(sort_dim) != 1) { // In case of a sort operand sharded along the sort dimension, the // sharding is propagated only if there exists a free (unsharded) // dimension that we can later move the sharding into. if (!hlo_sharding_util::IsSortOperandShardingMovable(operand, sort_dim)) return false; } if (instruction->shape().IsTuple()) { return MaybeImproveInstructionSharding( HloSharding::SingleTuple(instruction->shape(), operand->sharding()), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); } else { return MaybeImproveInstructionSharding( operand->sharding(), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); } } case HloOpcode::kDynamicSlice: case HloOpcode::kDynamicUpdateSlice: { return InferDynamicSliceOrDynamicUpdateSliceShardingFromOperands( instruction, aggressiveness, may_combine_partial_sharding); } case HloOpcode::kGather: { bool changed = false; if (hlo_sharding_util::IsSpatiallyPartitioned(instruction->operand(1))) { HloSharding new_sharding = hlo_sharding_util:: GatherOutputShardingFromIndexIndexPassthroughDimensions( instruction->operand(1)->sharding(), instruction); changed |= MaybeImproveInstructionSharding( std::move(new_sharding), instruction, may_combine_partial_sharding); } if (is_spmd_) { auto gather_parallel_dims = hlo_sharding_util::GetGatherParallelBatchDims(*instruction, call_graph); if (gather_parallel_dims) { changed |= InferGatherParallelShardingFromOperands( instruction, *gather_parallel_dims, may_combine_partial_sharding); } if (hlo_sharding_util::IsSpatiallyPartitioned( instruction->operand(0))) { absl::Span<const int64_t> operand_parallel_dims; if (gather_parallel_dims) { operand_parallel_dims = absl::MakeConstSpan( gather_parallel_dims->operand_parallel_dims); } HloSharding filtered_operand_sharding = hlo_sharding_util::PartiallyReplicateTiledShardingOnDims( instruction->operand(0)->sharding(), operand_parallel_dims); auto maybe_from_data = hlo_sharding_util:: GatherOutputShardingFromOperandOperandPassthroughDimensions( filtered_operand_sharding, *instruction); if (maybe_from_data) { changed |= MaybeImproveInstructionSharding( std::move(*maybe_from_data), instruction, may_combine_partial_sharding); } } } return changed; } case HloOpcode::kScatter: { auto& scatter = *Cast<HloScatterInstruction>(instruction); const int64_t operand_count = scatter.scatter_operand_count(); auto scatter_operands = scatter.scatter_operands(); auto scatter_indices = scatter.scatter_indices(); auto scatter_updates = scatter.scatter_updates(); bool changed = false; if (is_spmd_) { for (int64_t i = 0; i != operand_count; ++i) { if (hlo_sharding_util::IsSpatiallyPartitioned(scatter_operands[i])) { changed |= MaybeImproveInstructionSubSharding( scatter_operands[i]->sharding(), instruction, {i}, may_combine_partial_sharding); } } if (!hlo_sharding_util::IsSpatiallyPartitioned(scatter_indices) && absl::c_none_of(scatter_updates, [](const HloInstruction* update) { return hlo_sharding_util::IsSpatiallyPartitioned(update); })) { return changed; } auto scatter_parallel_dims = hlo_sharding_util::GetScatterParallelBatchDims(*instruction, call_graph); if (scatter_parallel_dims) { changed |= InferScatterParallelShardingFromOperands( instruction, *scatter_parallel_dims, may_combine_partial_sharding); } for (int64_t i = 0; i != operand_count; ++i) { if (hlo_sharding_util::IsSpatiallyPartitioned(scatter_updates[i])) { auto maybe_from_update = hlo_sharding_util::ScatterOutputShardingFromUpdate( scatter_updates[i]->sharding(), scatter); if (maybe_from_update) { changed |= MaybeImproveInstructionSubSharding( std::move(*maybe_from_update), instruction, {i}, may_combine_partial_sharding); } } } } else { for (int64_t i = 0; i != operand_count; ++i) { changed |= MaybeImproveInstructionSubSharding( HloSharding::Replicate(), instruction, {i}, may_combine_partial_sharding); } } return changed; } case HloOpcode::kWhile: { if (!instruction->operand(0)->has_sharding()) { return false; } auto sharding = instruction->operand(0)->sharding(); if (instruction->has_sharding()) { hlo_sharding_util::MergeSharding(instruction->sharding(), &sharding, may_combine_partial_sharding); } return MaybeImproveInstructionSharding(std::move(sharding), instruction, may_combine_partial_sharding); } case HloOpcode::kCustomCall: { HloSharding inferred_operand_sharding = HloSharding::Replicate(); if (auto* partitioner = GetCustomCallPartitioner(instruction->custom_call_target()); partitioner && partitioner->IsCustomCallShardable(instruction)) { if (auto sharding = partitioner->InferShardingFromOperands(instruction)) { inferred_operand_sharding = *sharding; } else { return false; } } else if (sharding_helper_->IsCustomCallShardable(instruction)) { if (auto sharding = sharding_helper_->InferShardingFromOperands(instruction)) { inferred_operand_sharding = *sharding; } else { return false; } } else { const HloInstruction* operand = PickRepresentativeOperand(instruction); if (!operand || !hlo_sharding_util::IsSpatiallyPartitioned(operand)) { return false; } inferred_operand_sharding = operand->sharding(); } return MaybeImproveInstructionSharding( inferred_operand_sharding, instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ComputeNonRootUsers(instruction) == 1); } default: { if (instruction->IsElementwise() && may_combine_partial_sharding) { bool changed = false; for (auto operand : instruction->operands()) { if (hlo_sharding_util::IsSpatiallyPartitioned(operand)) { if (instruction->opcode() == HloOpcode::kRng) { // Rng is considered elementwise but has operands with different // shapes. changed |= MaybeImproveInstructionSharding( hlo_sharding_util::ReplicateAllDataDims( operand->sharding(), instruction->shape().rank()), instruction, may_combine_partial_sharding, ComputeNonRootUsers(instruction) == 1); continue; } changed |= MaybeImproveInstructionSharding( operand->sharding(), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ instruction->operands().size() == 1 && ComputeNonRootUsers(instruction) == 1); } } return changed; } const HloInstruction* operand = PickRepresentativeOperand(instruction); if (!operand || !hlo_sharding_util::IsSpatiallyPartitioned(operand)) { return false; } return MaybeImproveInstructionSharding( operand->sharding(), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ComputeNonRootUsers(instruction) == 1); } } return false; } // NOLINT(readability/fn_size) auto get_maybe_tuple_sharding = [&](HloSharding sharding) { if (instruction->shape().IsArray()) { return sharding; } std::vector<HloSharding> tuple(instruction->shape().tuple_shapes_size(), std::move(sharding)); return HloSharding::Tuple(instruction->shape(), tuple); }; auto is_more_specific = [instruction](const HloSharding& operand_sharding, const HloSharding& existing) { // If the instruction originally had no sharding, always prefer operand // sharding. return !instruction->has_sharding() || hlo_sharding_util::IsShardingMoreSpecific(operand_sharding, existing); }; VLOG(2) << "Not applying sharding to reduce window because dilatation " VLOG(2) << "Not applying sharding to select-and-scatter because " bool ShardingPropagation::InferShardingFromUsers( HloInstruction* instruction, const ShardingPropagation::ComputationMap& computation_map, int64_t aggressiveness, bool is_spmd, const CustomCallShardingHelper* sharding_helper, const CallGraph& call_graph) { if (aggressiveness < 2 && instruction->opcode() == HloOpcode::kBroadcast) { return false; } // Do not change manual sharding. if (instruction->has_sharding() && instruction->sharding().IsManual()) { return false; } // Propagate manual sharding. if (!instruction->has_sharding() || instruction->sharding().IsTileMaximal()) { for (const HloInstruction* user : instruction->users()) { if (!user->has_sharding() || user->IsCustomCall("SPMDFullToShardShape")) continue; if (instruction->shape().IsArray() && user->sharding().IsManual()) { instruction->set_sharding( HloSharding::Manual(user->sharding().metadata())); return true; } else { std::optional<HloSharding> user_sharding = ShardingPropagation::GetShardingFromUser( *instruction, *user, aggressiveness, is_spmd, call_graph, sharding_helper); if (user_sharding && user_sharding->IsManual()) { instruction->set_sharding(std::move(*user_sharding)); return true; } } } } if (!SupportSpatialPartitioning( instruction, computation_map, is_spmd, /*allow_spmd_sharding_propagation_to_output=*/false, allow_spmd_sharding_propagation_to_parameters_, sharding_helper)) { return false; } bool improved_sharding = false; const bool may_combine_partial_sharding = is_spmd && aggressiveness > 0; for (const HloInstruction* user : instruction->users()) { std::optional<HloSharding> user_sharding = ShardingPropagation::GetShardingFromUser(*instruction, *user, aggressiveness, is_spmd, call_graph, sharding_helper); if (user_sharding && instruction->opcode() == HloOpcode::kCustomCall) { if (auto* partitioner = GetCustomCallPartitioner(instruction->custom_call_target())) { if (partitioner->IsCustomCallShardable(instruction)) { user_sharding = partitioner->PropagateUserSharding(instruction, user, *user_sharding); } } else if (sharding_helper->IsCustomCallShardable(instruction)) { user_sharding = sharding_helper->PropagateUserSharding( instruction, user, *user_sharding); } } if (user_sharding) { improved_sharding |= MaybeImproveInstructionSharding( std::move(*user_sharding), instruction, may_combine_partial_sharding); } } return improved_sharding; } absl::StatusOr<bool> ShardingPropagation::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { // Register custom-call partitioner for SharBarrierFrom and ShardBarrierTo. ABSL_CONST_INIT static absl::once_flag did_registration; absl::call_once(did_registration, [] { RegisterCustomCallPartitioner( spmd::kShardBarrierFrom, std::make_unique<spmd::ShardBarrierFromPartitioner>()); RegisterCustomCallPartitioner( spmd::kShardBarrierTo, std::make_unique<spmd::ShardBarrierToPartitioner>()); }); std::optional<absl::flat_hash_map<const HloInstruction*, HloSharding>> original_sharding; bool any_changed = false; // Preprocessing for CSE prevention propagation: record the original shardings // so that we can revert to them at the end, and only keep those on CSE // prevention instructions. if (cse_prevention_only_) { original_sharding.emplace(); for (auto computation : module->computations(execution_threads)) { for (auto instruction : computation->instructions()) { if (instruction->has_sharding()) { original_sharding->emplace(instruction, instruction->sharding()); } } } } else { // The current pass is not for CSE prevention, but we remove the shardings // added by previous passes for CSE prevention. for (auto computation : module->computations(execution_threads)) { for (auto instruction : computation->instructions()) { if (instruction->has_sharding() && IsCSEPreventionSharding(instruction->sharding())) { instruction->clear_sharding(); any_changed = true; } } } } any_changed |= propagate_metadata_ ? AssignShardingMetadata(module, execution_threads) : RemoveShardingMetadata(module, execution_threads); absl::flat_hash_map<const HloInstruction*, std::vector<int64_t>> unspecified_dims; std::vector<HloSharding> saved_root_shardings; absl::flat_hash_map<int64_t, HloSharding> saved_parameter_shardings; absl::flat_hash_map<HloInstruction*, int64_t> instruction_to_shard_group_id; absl::flat_hash_map<int64_t, absl::flat_hash_set<HloInstruction*>> shard_group_id_to_shard_as_group; absl::flat_hash_map<int64_t, absl::flat_hash_set<HloInstruction*>> shard_group_id_to_shard_like_group; TF_ASSIGN_OR_RETURN( bool changed, ProcessShardingInstruction( module, execution_threads, !cse_prevention_only_, &unspecified_dims, allow_spmd_sharding_propagation_to_output_ ? &saved_root_shardings : nullptr, allow_spmd_sharding_propagation_to_parameters_ ? &saved_parameter_shardings : nullptr, &instruction_to_shard_group_id, &shard_group_id_to_shard_as_group, &shard_group_id_to_shard_like_group, &allow_spmd_sharding_propagation_to_parameters_vector_)); any_changed |= changed; for (const auto& [shard_group_id, shard_as_group] : shard_group_id_to_shard_as_group) { VLOG(5) << "Shard-As group " << shard_group_id << " contains:"; for (auto instruction : shard_as_group) { VLOG(5) << " " << instruction->ToString(); } } for (const auto& [shard_group_id, shard_like_group] : shard_group_id_to_shard_like_group) { VLOG(5) << "Shard-Like group " << shard_group_id << " contains:"; for (auto instruction : shard_like_group) { VLOG(5) << " " << instruction->ToString(); } } // Check sizes of the given allow_spmd_sharding_propagation vectors if (allow_spmd_sharding_propagation_to_output_) { CHECK(!module->entry_computation()->root_instruction()->has_sharding() || allow_spmd_sharding_propagation_to_output_vector_.size() == 1 || module->entry_computation() ->root_instruction() ->sharding() .tuple_elements() .size() == allow_spmd_sharding_propagation_to_output_vector_.size()) << "allow-spmd-sharding-propagation-to-output-vector's size can be " "either 1 or the number of elements in the root tuple of entry " "computation."; } if (allow_spmd_sharding_propagation_to_parameters_) { auto is_same_sized_tuple = [](HloModule* module, int64_t size) { if (module->entry_computation()->num_parameters() != 1) { return false; } HloInstruction* param = module->entry_computation()->parameter_instruction(0); return param->shape().IsTuple() && size == param->shape().tuple_shapes_size(); }; auto size = allow_spmd_sharding_propagation_to_parameters_vector_.size(); CHECK(size == 1 || size == module->entry_computation()->num_parameters() || is_same_sized_tuple(module, size)) << "allow-spmd-sharding-propagation-to-parameters-vector's size can be " "either 1 or the number of parameters in the entry computation."; } // Association of partitionable embedded computations with their parent // instruction. ComputationMap computation_map; // Instructions that are related through a computation and need to share the // same sharding. auto get_related_instructions = [this](HloInstruction* inst) { if (inst->opcode() == HloOpcode::kWhile) { return std::vector<HloInstruction*>{ inst, inst->while_body()->root_instruction(), inst->while_body()->parameter_instruction(0), inst->while_condition()->parameter_instruction(0)}; } else if (inst->opcode() == HloOpcode::kConditional) { const auto& called_computations = inst->called_computations(); std::vector<HloInstruction*> comps; comps.reserve(called_computations.size() + 1); comps.push_back(inst); for (HloComputation* c : called_computations) { comps.push_back(c->root_instruction()); } return comps; } else if (inst->opcode() == HloOpcode::kCustomCall) { if (sharding_helper_ && sharding_helper_->IsCustomCallShardable(inst)) { return sharding_helper_->GetRelatedInstructions(inst); } else { return std::vector<HloInstruction*>{}; } } else if (inst->opcode() == HloOpcode::kCall) { HloComputation* callee = inst->called_computations().front(); return std::vector<HloInstruction*>{inst, callee->root_instruction()}; } else { CHECK(false); } }; // If instruction is a while, or the root or a parameter of a while body, // then propagate its sharding to the while instruction, to its body root, // and to its condition parameter. std::function<void(HloInstruction*, absl::flat_hash_set<HloInstruction*>*)> maybe_computation_propagation = [&](HloInstruction* instruction, absl::flat_hash_set<HloInstruction*>* changed) { auto propagate_to_instruction = [&](HloInstruction* search_inst) { auto related_instructions = get_related_instructions(search_inst); if (absl::c_count(related_instructions, instruction)) { for (HloInstruction* inst : related_instructions) { if (!inst->has_sharding() || inst->sharding() != instruction->sharding()) { VLOG(2) << "Add computation sharding: " << inst->name() << " " << instruction->sharding().ToString(); inst->copy_sharding(instruction); changed->insert(inst); maybe_computation_propagation(inst, changed); } } } }; if (instruction->opcode() == HloOpcode::kConditional || instruction->opcode() == HloOpcode::kWhile || instruction->opcode() == HloOpcode::kCustomCall || instruction->opcode() == HloOpcode::kCall) { propagate_to_instruction(instruction); } if (instruction->opcode() == HloOpcode::kParameter || instruction->parent()->root_instruction() == instruction) { auto it = computation_map.find(instruction->parent()); if (it != computation_map.end()) { propagate_to_instruction(it->second); } } }; for (auto computation : module->computations(execution_threads)) { for (auto instruction : computation->instructions()) { if (instruction->opcode() == HloOpcode::kWhile) { TF_RETURN_IF_ERROR( CheckAndUpdateDeviceAssignmentsInWhileBody(instruction)); } } } // Populate computation_map in order to associate while bodies to their // while instructions. for (auto computation : module->computations(execution_threads)) { for (auto instruction : computation->instructions()) { if (instruction->opcode() == HloOpcode::kWhile || instruction->opcode() == HloOpcode::kConditional || instruction->opcode() == HloOpcode::kCall) { // Check if any of the related instructions has sharding, in which case // propagate it to the other instructions, so they all share the same // sharding, in case the user didn't shard all of them. We don't check // that user shardings are consistent, because such check is already // done by HLO verifier. const HloInstruction* sharded_inst = nullptr; auto related_instructions = get_related_instructions(instruction); for (auto inst : related_instructions) { if (inst->has_sharding()) { sharded_inst = inst; break; } } if (sharded_inst != nullptr) { // Set the same sharding to all the other related instructions. for (auto inst : related_instructions) { inst->copy_sharding(sharded_inst); } } if (instruction->opcode() == HloOpcode::kWhile) { computation_map[instruction->while_body()] = instruction; } else { for (HloComputation* c : instruction->called_computations()) { computation_map[c] = instruction; } } } } } // Collect all pre-sharded instructions as we aren't allowed to modify their // sharding. absl::flat_hash_set<const HloInstruction*> provided_shardings; for (const HloComputation* computation : module->computations(execution_threads)) { for (const HloInstruction* inst : computation->instructions()) { if (inst->has_sharding() && inst != module->entry_computation()->root_instruction() && inst->opcode() != HloOpcode::kParameter && !inst->sharding().IsUnknown()) { provided_shardings.insert(inst); } } } if (!allow_spmd_sharding_propagation_to_output_ && (!module->entry_computation()->root_instruction()->has_sharding() || !module->entry_computation() ->root_instruction() ->sharding() .IsUnknown())) { // Consider the root instruction of the entry module as one with provided // sharding as its sharding have to match with the one expected by the host. provided_shardings.insert(module->entry_computation()->root_instruction()); } if (!allow_spmd_sharding_propagation_to_parameters_) { for (auto param : module->entry_computation()->parameter_instructions()) { if (param->has_sharding() && !param->sharding().IsUnknown()) { provided_shardings.insert(param); } } } // Replace all unknown shardings with replicated sharding for propagation. for (HloComputation* computation : module->computations(execution_threads)) { auto instructions = computation->MakeInstructionPostOrder(); for (auto it = instructions.rbegin(); it != instructions.rend(); ++it) { HloInstruction* instruction = *it; if (instruction->has_sharding() && instruction->sharding().IsUnknown()) { instruction->set_sharding( HloSharding::Replicate(instruction->sharding().metadata())); } } } // Iterate to a fixpoint that is guaranteed to be reached because we only // strictly improve the sharding of the graph and it can't be improved // indefinitely. int64_t iterations = 0; std::unique_ptr<CallGraph> call_graph = CallGraph::Build(module); auto run_to_fix_point = [&](int64_t aggressiveness, bool propagate_shard_group) { absl::flat_hash_set<const HloInstruction*> already_inferred_from_shard_group; absl::flat_hash_set<const HloInstruction*> already_inferred_from_operands; absl::flat_hash_set<const HloInstruction*> already_inferred_from_users; bool changed_last_iter = true; const bool may_merge_partial = is_spmd_ && aggressiveness > 0; while (changed_last_iter) { changed_last_iter = false; int64_t inferred_from_shard_group_counter = 0; int64_t inferred_from_operand_counter = 0; int64_t inferred_from_user_counter = 0; int64_t instruction_counter = 0; int64_t already_sharded_counter = 0; for (const HloComputation* computation : module->computations(execution_threads)) { VLOG(2) << "Consider computation: " << computation->name(); std::vector<HloInstruction*> instructions = computation->MakeInstructionPostOrder(); instruction_counter += instructions.size(); already_sharded_counter += absl::c_count_if( instructions, [](const HloInstruction* inst) { return inst->has_sharding(); }); auto clear_cache = [&](HloInstruction* hlo, HloInstruction* hlo_for_users = nullptr) { for (auto operand : hlo->operands()) { already_inferred_from_users.erase(operand); } if (hlo_for_users == nullptr) { hlo_for_users = hlo; } for (auto user : hlo_for_users->users()) { already_inferred_from_operands.erase(user); // If the user has called computations, then the parameter // instructions of these called computations are also removed from // already_inferred_from_operands. for (auto c : user->called_computations()) { for (auto parameter : c->parameter_instructions()) { already_inferred_from_operands.erase(parameter); } } } if (instruction_to_shard_group_id.contains(hlo)) { const int64_t shard_group_id = instruction_to_shard_group_id.at(hlo); const absl::flat_hash_set<HloInstruction*>& shard_group = shard_group_id_to_shard_as_group.contains(shard_group_id) ? shard_group_id_to_shard_as_group.at(shard_group_id) : shard_group_id_to_shard_like_group.at(shard_group_id); for (HloInstruction* member : shard_group) { if (member != hlo) { already_inferred_from_shard_group.erase(member); } } } }; // 1. Iterate the shard groups to take shardings from instructions of // the same group. if (propagate_shard_group) { for (HloInstruction* instruction : instructions) { if (already_inferred_from_shard_group.contains(instruction)) { continue; } if (!instruction_to_shard_group_id.contains(instruction)) { continue; } const int64_t shard_group_id = instruction_to_shard_group_id.at(instruction); const absl::flat_hash_set<HloInstruction*>& shard_group = shard_group_id_to_shard_as_group.contains(shard_group_id) ? shard_group_id_to_shard_as_group.at(shard_group_id) : shard_group_id_to_shard_like_group.at(shard_group_id); if (provided_shardings.contains(instruction)) { if (!may_merge_partial) { continue; } auto it = unspecified_dims.find(instruction); if (it != unspecified_dims.end() && InferUnspecifiedDimsFromShardGroup(instruction, it->second, shard_group)) { ++inferred_from_shard_group_counter; VLOG(2) << "Refined partial sharding (shard group): " << instruction->ToString(); clear_cache(instruction); already_inferred_from_shard_group.insert(instruction); changed_last_iter = true; } continue; } already_inferred_from_shard_group.insert(instruction); if (InferShardingFromShardGroup(instruction, computation_map, aggressiveness, shard_group)) { ++inferred_from_shard_group_counter; any_changed = true; VLOG(2) << "Add sharding (shard group): " << instruction->ToString(); absl::flat_hash_set<HloInstruction*> changed_in_comp_prop; maybe_computation_propagation(instruction, &changed_in_comp_prop); clear_cache(instruction); for (auto hlo : changed_in_comp_prop) { clear_cache(hlo); } changed_last_iter = true; } } } // 2. Iterate the HLO graph in post order taking shardings from // operands. for (HloInstruction* instruction : instructions) { if (already_inferred_from_operands.contains(instruction)) { continue; } if (provided_shardings.contains(instruction)) { if (!may_merge_partial) { continue; } auto it = unspecified_dims.find(instruction); HloInstruction* man_conversion_op_after; if (it != unspecified_dims.end() && InferUnspecifiedDimsFromOperand(instruction, it->second, &man_conversion_op_after)) { ++inferred_from_operand_counter; VLOG(2) << "Refined partial sharding (forward-pass): " << instruction->ToString(); clear_cache(instruction, man_conversion_op_after); already_inferred_from_operands.insert(instruction); changed_last_iter = true; } continue; } already_inferred_from_operands.insert(instruction); if (InferShardingFromOperands(instruction, computation_map, aggressiveness, *call_graph, execution_threads)) { ++inferred_from_operand_counter; any_changed = true; VLOG(2) << "Add sharding (forward-pass): " << instruction->ToString(); absl::flat_hash_set<HloInstruction*> changed_in_comp_prop; maybe_computation_propagation(instruction, &changed_in_comp_prop); clear_cache(instruction); for (auto hlo : changed_in_comp_prop) { clear_cache(hlo); } changed_last_iter = true; } } // 3. Iterate the HLO graph in reverse post order taking shardings from // users. for (auto it = instructions.rbegin(); it != instructions.rend(); ++it) { if ((*it)->IsCustomCall("SPMDFullToShardShape") || (*it)->IsCustomCall("SPMDShardToFullShape")) { // The manual conversion op is processed together with the sharding // op before it. If the conversion op is removed from cache, the // sharding op should also be removed. if (!already_inferred_from_users.contains(*it)) { already_inferred_from_users.erase((*it)->operand(0)); } } if (already_inferred_from_users.contains(*it)) { continue; } if (provided_shardings.contains(*it)) { if (!may_merge_partial) { continue; } auto uit = unspecified_dims.find(*it); HloInstruction* man_conversion_op_after; if (uit != unspecified_dims.end() && InferUnspecifiedDimsFromUsers( *it, uit->second, aggressiveness, is_spmd_, &man_conversion_op_after, *call_graph)) { ++inferred_from_user_counter; VLOG(2) << "Refined partial sharding (backward-pass): " << (*it)->ToString(); clear_cache(*it, man_conversion_op_after); already_inferred_from_users.insert(*it); if (man_conversion_op_after != nullptr) { already_inferred_from_users.insert(man_conversion_op_after); } changed_last_iter = true; } continue; } already_inferred_from_users.insert(*it); if (InferShardingFromUsers(*it, computation_map, aggressiveness, is_spmd_, sharding_helper_.get(), *call_graph)) { ++inferred_from_user_counter; any_changed = true; VLOG(2) << "Add sharding (backward-pass): " << (*it)->ToString(); absl::flat_hash_set<HloInstruction*> changed_in_comp_prop; maybe_computation_propagation(*it, &changed_in_comp_prop); clear_cache(*it); for (auto hlo : changed_in_comp_prop) { clear_cache(hlo); } changed_last_iter = true; } } } VLOG(1) << "Sharding propagation iteration " << iterations << ";" << "\n total instructions: " << instruction_counter << "\n instructions already sharded: " << already_sharded_counter << "\n shardings inferred from shard group: " << inferred_from_shard_group_counter << "\n shardings inferred from operands: " << inferred_from_operand_counter << "\n shardings inferred from users: " << inferred_from_user_counter << "\n aggressiveness: " << aggressiveness; ++iterations; } return absl::OkStatus(); }; for (int64_t aggressiveness = 0; aggressiveness < 4; ++aggressiveness) { TF_RETURN_IF_ERROR( run_to_fix_point(aggressiveness, /*propagate_shard_group=*/true)); } // Align the shardings from the same shard_as group so that they will adopt // the same sharding. for (const auto& [shard_as_group_id, shard_as_group] : shard_group_id_to_shard_as_group) { // If all the inferred shardings of the instructions from the same shard // group are compatible with each other, then we will merge all of them to // get the most specific sharding. If some of them are not compatible, then // it will just choose the a random sharding among them(say the first one), // with the guarantee that the defaultly chosen sharding will not be from a // ShardBarrierFrom op if there is one within the ShardAs group. HloSharding default_sharding = HloSharding::Replicate(); std::vector<HloSharding> shardings; for (HloInstruction* instruction : shard_as_group) { if (instruction->has_sharding()) { shardings.push_back(instruction->sharding()); if (!instruction->IsCustomCall(spmd::kShardBarrierFrom) && default_sharding.IsReplicated()) { default_sharding = instruction->sharding(); } } } HloSharding common_sharding = hlo_sharding_util::FindCommonSharding(shardings, default_sharding); VLOG(2) << "Aligning shard group: " << shard_as_group_id << " to sharding:" << common_sharding.ToString(); for (HloInstruction* member : shard_as_group) { if (member->IsCustomCall(spmd::kShardBarrierTo)) { continue; } if (provided_shardings.contains(member)) { auto it = unspecified_dims.find(member); if (it != unspecified_dims.end()) { HloSharding partial_replicated = hlo_sharding_util::PartiallyReplicateTiledShardingOnAllDimsExcept( common_sharding, it->second); HloSharding sharding = member->sharding(); if (hlo_sharding_util::MergeShardingIfCompatible( partial_replicated, sharding.NumTiles() + 1, &sharding)) { member->set_sharding(sharding); } } } member->set_sharding(common_sharding); } } // If a ShardBarrierFrom custom-call op is in a shard as group, and relay // the shard as sharding to its original op, do not relay shardings for // ShardbarrierTo op. Then run sharding propagation once more at highest // aggressiveness without propagating shard group. for (HloComputation* computation : module->computations(execution_threads)) { for (HloInstruction* instruction : computation->instructions()) { if (instruction->IsCustomCall(spmd::kShardBarrierFrom) && instruction_to_shard_group_id.contains(instruction) && shard_group_id_to_shard_as_group.contains( instruction_to_shard_group_id.at(instruction))) { HloSharding sharding = instruction->sharding(); hlo_sharding_util::MergeShardingIfCompatible( instruction->mutable_operand(0)->sharding(), sharding.NumTiles(), &sharding); instruction->mutable_operand(0)->set_sharding(std::move(sharding)); } } } TF_RETURN_IF_ERROR( run_to_fix_point(/*aggressiveness=*/3, /*propagate_shard_group=*/false)); // Post-process to remove all "shard-barrier-from" and "shard-barrier-to" // custom-calls. for (HloComputation* computation : module->computations(execution_threads)) { for (HloInstruction* instruction : computation->instructions()) { // If a ShardBarrierFrom custom-call op is in a shard as group, and relay // the shard as sharding to its original op, do not relay shardings for // ShardbarrierTo op. if (instruction->IsCustomCall(spmd::kShardBarrierFrom) && instruction_to_shard_group_id.contains(instruction) && shard_group_id_to_shard_as_group.contains( instruction_to_shard_group_id.at(instruction))) { HloSharding sharding = instruction->sharding(); hlo_sharding_util::MergeShardingIfCompatible( instruction->mutable_operand(0)->sharding(), sharding.NumTiles(), &sharding); instruction->mutable_operand(0)->set_sharding(std::move(sharding)); } if (instruction->IsCustomCall(spmd::kShardBarrierFrom) || instruction->IsCustomCall(spmd::kShardBarrierTo)) { TF_ASSIGN_OR_RETURN(std::ignore, computation->ReplaceInstruction( instruction, instruction->mutable_operand(0), /*preserve_sharding=*/false, /*relay_control_dependency=*/false, /*remove_unused_operands=*/false)); } } } // Post-process for CSE prevention. if (cse_prevention_only_) { for (auto computation : module->computations(execution_threads)) { for (auto instruction : computation->instructions()) { if (!instruction->has_sharding()) { continue; } if (IsCSEPreventionTarget(instruction) && instruction->has_sharding()) { if (!(*original_sharding).contains(instruction)) { // Mark the propagated sharding as for CSE prevention. instruction->set_sharding( SetCSEPreventionSharding(instruction->sharding())); } continue; } auto it = (*original_sharding).find(instruction); if (it != (*original_sharding).end()) { // Revert sharding. instruction->set_sharding(it->second); } else { // Clear sharding. instruction->clear_sharding(); } } } } HloInstruction* root_instruction = module->entry_computation()->root_instruction(); if (saved_root_shardings.size() == allow_spmd_sharding_propagation_to_output_vector_.size() && root_instruction->has_sharding()) { HloSharding root_sharding = root_instruction->sharding(); for (int i = 0; i < saved_root_shardings.size(); ++i) { if (!allow_spmd_sharding_propagation_to_output_vector_[i] && !saved_root_shardings[i].IsUnknown()) { root_sharding.tuple_elements()[i] = saved_root_shardings[i]; } } root_instruction->set_sharding(std::move(root_sharding)); } auto params = module->entry_computation()->parameter_instructions(); if (allow_spmd_sharding_propagation_to_parameters_) { if (allow_spmd_sharding_propagation_to_parameters_vector_.size() == params.size()) { for (int64_t i = 0; i < params.size(); ++i) { if (!allow_spmd_sharding_propagation_to_parameters_vector_[i]) { if (saved_parameter_shardings.contains(i) && !saved_parameter_shardings.at(i).IsUnknown()) { params[i]->set_sharding(saved_parameter_shardings.at(i)); } else { params[i]->clear_sharding(); } } } } else if (params.size() == 1 && saved_parameter_shardings.size() == 1 && params[0]->shape().IsTuple() && params[0]->shape().tuple_shapes_size() == allow_spmd_sharding_propagation_to_parameters_vector_ .size()) { // There is a single parameter which is a tuple with many elements. HloSharding param_sharding = params[0]->sharding(); for (int64_t i = 0; i < params[0]->shape().tuple_shapes_size(); ++i) { HloSharding saved_subsharding = saved_parameter_shardings.at(0).GetSubSharding(params[0]->shape(), {i}); if (!allow_spmd_sharding_propagation_to_parameters_vector_[i] && !saved_subsharding.IsUnknown()) { param_sharding.tuple_elements()[i] = saved_subsharding; } } params[0]->set_sharding(std::move(param_sharding)); } } // Replicate the parameter/output sharding if the propagated sharding does not // evenly partition the parameter/output. std::function<bool(const Shape&, const HloSharding&)> evenly_partitions = [&evenly_partitions](const Shape& shape, const HloSharding& sharding) -> bool { if (!sharding.IsTiled()) { return true; } if (sharding.IsTileMaximal()) { return sharding.IsReplicated(); } if (sharding.IsTuple()) { for (int64_t i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { if (!evenly_partitions(ShapeUtil::GetTupleElementShape(shape, i), sharding.GetSubSharding(shape, {i}))) { return false; } } } for (int64_t i = 0; i < shape.dimensions_size(); ++i) { if (shape.dimensions(i) % sharding.tile_assignment().dim(i) != 0) { return false; } } return true; }; if (allow_spmd_sharding_propagation_to_output_ && root_instruction->has_sharding()) { if (root_instruction->shape().IsTuple() && allow_spmd_sharding_propagation_to_output_vector_.size() == root_instruction->shape().tuple_shapes_size()) { // The output shape is a tuple and sharding propagation is allowed for at // least one of its elements. HloSharding root_sharding = root_instruction->sharding(); for (int64_t i = 0; i < root_instruction->shape().tuple_shapes_size(); ++i) { if (allow_spmd_sharding_propagation_to_output_vector_[i] && !evenly_partitions(root_instruction->shape().tuple_shapes(i), root_sharding.tuple_elements()[i])) { root_sharding.tuple_elements()[i] = HloSharding::Replicate(); } } root_instruction->set_sharding(std::move(root_sharding)); } else if (!root_instruction->shape().IsTuple()) { // The output shape is not tuple and sharding propagation is allowed. if (!evenly_partitions(root_instruction->shape(), root_instruction->sharding())) { root_instruction->set_sharding(HloSharding::Replicate()); } } } if (allow_spmd_sharding_propagation_to_parameters_) { // Sharding propagation is allowed for at least one parameter. if (allow_spmd_sharding_propagation_to_parameters_vector_.size() == params.size()) { for (int64_t i = 0; i < params.size(); ++i) { if (params[i]->has_sharding() && allow_spmd_sharding_propagation_to_parameters_vector_[i] && !evenly_partitions(params[i]->shape(), params[i]->sharding())) { params[i]->set_sharding(HloSharding::Replicate()); } } } else if (params.size() == 1 && params[0]->shape().IsTuple() && params[0]->has_sharding() && params[0]->shape().tuple_shapes_size() == allow_spmd_sharding_propagation_to_parameters_vector_ .size()) { HloSharding param_sharding = params[0]->sharding(); for (int64_t i = 0; i < params[0]->shape().tuple_shapes_size(); ++i) { if (allow_spmd_sharding_propagation_to_parameters_vector_[i] && !evenly_partitions( ShapeUtil::GetSubshapeOneIndex(params[0]->shape(), i), params[0]->sharding().GetSubSharding(params[0]->shape(), {i}))) { param_sharding.tuple_elements()[i] = HloSharding::Replicate(); } } params[0]->set_sharding(std::move(param_sharding)); } } TF_RETURN_IF_ERROR( hlo_sharding_util::CanonicalizeLayoutAfterShardingPropagation( module, allow_spmd_sharding_propagation_to_output_, allow_spmd_sharding_propagation_to_parameters_)); VLOG(1) << "Sharding propagation completed after " << iterations << " iterations"; return any_changed; } absl::call_once(did_registration, [] { RegisterCustomCallPartitioner( spmd::kShardBarrierFrom, std::make_unique<spmd::ShardBarrierFromPartitioner>()); RegisterCustomCallPartitioner( spmd::kShardBarrierTo, std::make_unique<spmd::ShardBarrierToPartitioner>()); }); VLOG(5) << "Shard-As group " << shard_group_id << " contains:"; VLOG(5) << " " << instruction->ToString(); VLOG(5) << "Shard-Like group " << shard_group_id << " contains:"; VLOG(5) << " " << instruction->ToString(); auto is_same_sized_tuple = [](HloModule* module, int64_t size) { if (module->entry_computation()->num_parameters() != 1) { return false; } HloInstruction* param = module->entry_computation()->parameter_instruction(0); return param->shape().IsTuple() && size == param->shape().tuple_shapes_size(); }; auto get_related_instructions = [this](HloInstruction* inst) { if (inst->opcode() == HloOpcode::kWhile) { return std::vector<HloInstruction*>{ inst, inst->while_body()->root_instruction(), inst->while_body()->parameter_instruction(0), inst->while_condition()->parameter_instruction(0)}; } else if (inst->opcode() == HloOpcode::kConditional) { const auto& called_computations = inst->called_computations(); std::vector<HloInstruction*> comps; comps.reserve(called_computations.size() + 1); comps.push_back(inst); for (HloComputation* c : called_computations) { comps.push_back(c->root_instruction()); } return comps; } else if (inst->opcode() == HloOpcode::kCustomCall) { if (sharding_helper_ && sharding_helper_->IsCustomCallShardable(inst)) { return sharding_helper_->GetRelatedInstructions(inst); } else { return std::vector<HloInstruction*>{}; } } else if (inst->opcode() == HloOpcode::kCall) { HloComputation* callee = inst->called_computations().front(); return std::vector<HloInstruction*>{inst, callee->root_instruction()}; } else { CHECK(false); } }; [&](HloInstruction* instruction, absl::flat_hash_set<HloInstruction*>* changed) { auto propagate_to_instruction = [&](HloInstruction* search_inst) { auto related_instructions = get_related_instructions(search_inst); if (absl::c_count(related_instructions, instruction)) { for (HloInstruction* inst : related_instructions) { if (!inst->has_sharding() || inst->sharding() != instruction->sharding()) { VLOG(2) << "Add computation sharding: " << inst->name() << " " << instruction->sharding().ToString(); inst->copy_sharding(instruction); changed->insert(inst); maybe_computation_propagation(inst, changed); } } } }; if (instruction->opcode() == HloOpcode::kConditional || instruction->opcode() == HloOpcode::kWhile || instruction->opcode() == HloOpcode::kCustomCall || instruction->opcode() == HloOpcode::kCall) { propagate_to_instruction(instruction); } if (instruction->opcode() == HloOpcode::kParameter || instruction->parent()->root_instruction() == instruction) { auto it = computation_map.find(instruction->parent()); if (it != computation_map.end()) { propagate_to_instruction(it->second); } } }; auto propagate_to_instruction = [&](HloInstruction* search_inst) { auto related_instructions = get_related_instructions(search_inst); if (absl::c_count(related_instructions, instruction)) { for (HloInstruction* inst : related_instructions) { if (!inst->has_sharding() || inst->sharding() != instruction->sharding()) { VLOG(2) << "Add computation sharding: " << inst->name() << " " << instruction->sharding().ToString(); inst->copy_sharding(instruction); changed->insert(inst); maybe_computation_propagation(inst, changed); } } } }; VLOG(2) << "Add computation sharding: " << inst->name() auto run_to_fix_point = [&](int64_t aggressiveness, bool propagate_shard_group) { absl::flat_hash_set<const HloInstruction*> already_inferred_from_shard_group; absl::flat_hash_set<const HloInstruction*> already_inferred_from_operands; absl::flat_hash_set<const HloInstruction*> already_inferred_from_users; bool changed_last_iter = true; const bool may_merge_partial = is_spmd_ && aggressiveness > 0; while (changed_last_iter) { changed_last_iter = false; int64_t inferred_from_shard_group_counter = 0; int64_t inferred_from_operand_counter = 0; int64_t inferred_from_user_counter = 0; int64_t instruction_counter = 0; int64_t already_sharded_counter = 0; for (const HloComputation* computation : module->computations(execution_threads)) { VLOG(2) << "Consider computation: " << computation->name(); std::vector<HloInstruction*> instructions = computation->MakeInstructionPostOrder(); instruction_counter += instructions.size(); already_sharded_counter += absl::c_count_if( instructions, [](const HloInstruction* inst) { return inst->has_sharding(); }); auto clear_cache = [&](HloInstruction* hlo, HloInstruction* hlo_for_users = nullptr) { for (auto operand : hlo->operands()) { already_inferred_from_users.erase(operand); } if (hlo_for_users == nullptr) { hlo_for_users = hlo; } for (auto user : hlo_for_users->users()) { already_inferred_from_operands.erase(user); // If the user has called computations, then the parameter // instructions of these called computations are also removed from // already_inferred_from_operands. for (auto c : user->called_computations()) { for (auto parameter : c->parameter_instructions()) { already_inferred_from_operands.erase(parameter); } } } if (instruction_to_shard_group_id.contains(hlo)) { const int64_t shard_group_id = instruction_to_shard_group_id.at(hlo); const absl::flat_hash_set<HloInstruction*>& shard_group = shard_group_id_to_shard_as_group.contains(shard_group_id) ? shard_group_id_to_shard_as_group.at(shard_group_id) : shard_group_id_to_shard_like_group.at(shard_group_id); for (HloInstruction* member : shard_group) { if (member != hlo) { already_inferred_from_shard_group.erase(member); } } } }; // 1. Iterate the shard groups to take shardings from instructions of // the same group. if (propagate_shard_group) { for (HloInstruction* instruction : instructions) { if (already_inferred_from_shard_group.contains(instruction)) { continue; } if (!instruction_to_shard_group_id.contains(instruction)) { continue; } const int64_t shard_group_id = instruction_to_shard_group_id.at(instruction); const absl::flat_hash_set<HloInstruction*>& shard_group = shard_group_id_to_shard_as_group.contains(shard_group_id) ? shard_group_id_to_shard_as_group.at(shard_group_id) : shard_group_id_to_shard_like_group.at(shard_group_id); if (provided_shardings.contains(instruction)) { if (!may_merge_partial) { continue; } auto it = unspecified_dims.find(instruction); if (it != unspecified_dims.end() && InferUnspecifiedDimsFromShardGroup(instruction, it->second, shard_group)) { ++inferred_from_shard_group_counter; VLOG(2) << "Refined partial sharding (shard group): " << instruction->ToString(); clear_cache(instruction); already_inferred_from_shard_group.insert(instruction); changed_last_iter = true; } continue; } already_inferred_from_shard_group.insert(instruction); if (InferShardingFromShardGroup(instruction, computation_map, aggressiveness, shard_group)) { ++inferred_from_shard_group_counter; any_changed = true; VLOG(2) << "Add sharding (shard group): " << instruction->ToString(); absl::flat_hash_set<HloInstruction*> changed_in_comp_prop; maybe_computation_propagation(instruction, &changed_in_comp_prop); clear_cache(instruction); for (auto hlo : changed_in_comp_prop) { clear_cache(hlo); } changed_last_iter = true; } } } // 2. Iterate the HLO graph in post order taking shardings from // operands. for (HloInstruction* instruction : instructions) { if (already_inferred_from_operands.contains(instruction)) { continue; } if (provided_shardings.contains(instruction)) { if (!may_merge_partial) { continue; } auto it = unspecified_dims.find(instruction); HloInstruction* man_conversion_op_after; if (it != unspecified_dims.end() && InferUnspecifiedDimsFromOperand(instruction, it->second, &man_conversion_op_after)) { ++inferred_from_operand_counter; VLOG(2) << "Refined partial sharding (forward-pass): " << instruction->ToString(); clear_cache(instruction, man_conversion_op_after); already_inferred_from_operands.insert(instruction); changed_last_iter = true; } continue; } already_inferred_from_operands.insert(instruction); if (InferShardingFromOperands(instruction, computation_map, aggressiveness, *call_graph, execution_threads)) { ++inferred_from_operand_counter; any_changed = true; VLOG(2) << "Add sharding (forward-pass): " << instruction->ToString(); absl::flat_hash_set<HloInstruction*> changed_in_comp_prop; maybe_computation_propagation(instruction, &changed_in_comp_prop); clear_cache(instruction); for (auto hlo : changed_in_comp_prop) { clear_cache(hlo); } changed_last_iter = true; } } // 3. Iterate the HLO graph in reverse post order taking shardings from // users. for (auto it = instructions.rbegin(); it != instructions.rend(); ++it) { if ((*it)->IsCustomCall("SPMDFullToShardShape") || (*it)->IsCustomCall("SPMDShardToFullShape")) { // The manual conversion op is processed together with the sharding // op before it. If the conversion op is removed from cache, the // sharding op should also be removed. if (!already_inferred_from_users.contains(*it)) { already_inferred_from_users.erase((*it)->operand(0)); } } if (already_inferred_from_users.contains(*it)) { continue; } if (provided_shardings.contains(*it)) { if (!may_merge_partial) { continue; } auto uit = unspecified_dims.find(*it); HloInstruction* man_conversion_op_after; if (uit != unspecified_dims.end() && InferUnspecifiedDimsFromUsers( *it, uit->second, aggressiveness, is_spmd_, &man_conversion_op_after, *call_graph)) { ++inferred_from_user_counter; VLOG(2) << "Refined partial sharding (backward-pass): " << (*it)->ToString(); clear_cache(*it, man_conversion_op_after); already_inferred_from_users.insert(*it); if (man_conversion_op_after != nullptr) { already_inferred_from_users.insert(man_conversion_op_after); } changed_last_iter = true; } continue; } already_inferred_from_users.insert(*it); if (InferShardingFromUsers(*it, computation_map, aggressiveness, is_spmd_, sharding_helper_.get(), *call_graph)) { ++inferred_from_user_counter; any_changed = true; VLOG(2) << "Add sharding (backward-pass): " << (*it)->ToString(); absl::flat_hash_set<HloInstruction*> changed_in_comp_prop; maybe_computation_propagation(*it, &changed_in_comp_prop); clear_cache(*it); for (auto hlo : changed_in_comp_prop) { clear_cache(hlo); } changed_last_iter = true; } } } VLOG(1) << "Sharding propagation iteration " << iterations << ";" << "\n total instructions: " << instruction_counter << "\n instructions already sharded: " << already_sharded_counter << "\n shardings inferred from shard group: " << inferred_from_shard_group_counter << "\n shardings inferred from operands: " << inferred_from_operand_counter << "\n shardings inferred from users: " << inferred_from_user_counter << "\n aggressiveness: " << aggressiveness; ++iterations; } return absl::OkStatus(); }; VLOG(2) << "Consider computation: " << computation->name(); auto clear_cache = [&](HloInstruction* hlo, HloInstruction* hlo_for_users = nullptr) { for (auto operand : hlo->operands()) { already_inferred_from_users.erase(operand); } if (hlo_for_users == nullptr) { hlo_for_users = hlo; } for (auto user : hlo_for_users->users()) { already_inferred_from_operands.erase(user); // If the user has called computations, then the parameter // instructions of these called computations are also removed from // already_inferred_from_operands. for (auto c : user->called_computations()) { for (auto parameter : c->parameter_instructions()) { already_inferred_from_operands.erase(parameter); } } } if (instruction_to_shard_group_id.contains(hlo)) { const int64_t shard_group_id = instruction_to_shard_group_id.at(hlo); const absl::flat_hash_set<HloInstruction*>& shard_group = shard_group_id_to_shard_as_group.contains(shard_group_id) ? shard_group_id_to_shard_as_group.at(shard_group_id) : shard_group_id_to_shard_like_group.at(shard_group_id); for (HloInstruction* member : shard_group) { if (member != hlo) { already_inferred_from_shard_group.erase(member); } } } }; VLOG(2) << "Refined partial sharding (shard group): " VLOG(2) << "Add sharding (shard group): " VLOG(2) << "Refined partial sharding (forward-pass): " VLOG(2) << "Add sharding (forward-pass): " VLOG(2) << "Refined partial sharding (backward-pass): " VLOG(2) << "Add sharding (backward-pass): " << (*it)->ToString(); VLOG(1) << "Sharding propagation iteration " << iterations << ";" VLOG(2) << "Aligning shard group: " << shard_as_group_id [&evenly_partitions](const Shape& shape, const HloSharding& sharding) -> bool { if (!sharding.IsTiled()) { return true; } if (sharding.IsTileMaximal()) { return sharding.IsReplicated(); } if (sharding.IsTuple()) { for (int64_t i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { if (!evenly_partitions(ShapeUtil::GetTupleElementShape(shape, i), sharding.GetSubSharding(shape, {i}))) { return false; } } } for (int64_t i = 0; i < shape.dimensions_size(); ++i) { if (shape.dimensions(i) % sharding.tile_assignment().dim(i) != 0) { return false; } } return true; }; VLOG(1) << "Sharding propagation completed after " << iterations
#include "xla/service/sharding_propagation.h" #include <ostream> #include <string> #include <utility> #include <vector> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/log/check.h" #include "absl/log/log.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/ir/hlo_op_metadata.h" #include "xla/hlo/ir/hlo_sharding.h" #include "xla/hlo/transforms/hlo_constant_splitter.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/protobuf_util.h" #include "xla/service/hlo_dce.h" #include "xla/service/hlo_parser.h" #include "xla/tests/hlo_test_base.h" #include "xla/util.h" #include "xla/xla_data.pb.h" #include "tsl/platform/statusor.h" TEST_F(ShardingPropagationTest, PropagateShardLikeDifferentSharding) { const char* const hlo_string = R"( HloModule module ENTRY %entry { p.0 = s32[16,16] parameter(0), sharding={devices=[4,2]0,1,2,3,4,5,6,7} p.1 = s32[16,16] parameter(1), sharding={devices=[2,4]0,1,2,3,4,5,6,7} add.1 = s32[16,16] add(p.0, p.0) sharding.1 = s32[16,16] custom-call(add.1), custom_call_target="Sharding", sharding={unknown shard_like 0} add.2 = s32[16,16] add(p.1, p.1) sharding.2 = s32[16,16] custom-call(add.2), custom_call_target="Sharding", sharding={unknown shard_like 0} ROOT mul = s32[16,16] multiply(add.1, add.2) })"; TF_ASSERT_OK_AND_ASSIGN(auto module, ParseAndReturnVerifiedModule(hlo_string)); TF_ASSERT_OK_AND_ASSIGN( bool changed, ShardingPropagation( /*is_spmd=*/true, /*propagate_metadata=*/true, /*allow_spmd_sharding_propagation_to_output=*/{true}, /*allow_spmd_sharding_propagation_to_parameters=*/{false, false}) .Run(module.get())); EXPECT_TRUE(changed); XLA_VLOG_LINES(1, module->ToString()); // Check dangling sharding custom-call can be removed by DCE after // propagation. auto* add_0 = FindInstruction(module.get(), "add.1"); ASSERT_NE(add_0, nullptr); auto* add_1 = FindInstruction(module.get(), "add.2"); ASSERT_NE(add_1, nullptr); // Check sharding is correctly propagated, and shard like wasn't able to force // the same sharding EXPECT_NE(add_0->sharding(), add_1->sharding()); }
ShardingPropagationTest_PropagateShardLikeSameSharding
xla/service/sharding_propagation_test.cc
std::optional<HloSharding> ReturnImprovedSharding( HloSharding sharding, HloInstruction* instruction, bool may_combine_partial_sharding, bool allow_aggressive_resharding = false) { return hlo_sharding_util::ReturnImprovedShardingImpl( std::move(sharding), instruction->has_sharding() ? &instruction->sharding() : nullptr, instruction->shape(), may_combine_partial_sharding, allow_aggressive_resharding); } std::optional<HloSharding> ReturnImprovedSubSharding( HloSharding sharding, HloInstruction* instruction, const ShapeIndex& index, bool may_combine_partial_sharding, bool allow_aggressive_resharding = false) { if (instruction->has_sharding()) { const HloSharding to_improved = instruction->sharding().GetSubSharding(instruction->shape(), index); return hlo_sharding_util::ReturnImprovedShardingImpl( std::move(sharding), &to_improved, ShapeUtil::GetSubshape(instruction->shape(), index), may_combine_partial_sharding, allow_aggressive_resharding); } else { return hlo_sharding_util::ReturnImprovedShardingImpl( std::move(sharding), nullptr, ShapeUtil::GetSubshape(instruction->shape(), index), may_combine_partial_sharding, allow_aggressive_resharding); } } bool MaybeImproveInstructionSharding(HloSharding sharding, HloInstruction* instruction, bool may_combine_partial_sharding, bool allow_aggressive_resharding = false) { if (auto new_sharding = ReturnImprovedSharding( std::move(sharding), instruction, may_combine_partial_sharding, allow_aggressive_resharding)) { instruction->set_sharding(std::move(*new_sharding)); return true; } return false; } bool MaybeImproveInstructionSubSharding( HloSharding sharding, HloInstruction* instruction, const ShapeIndex& index, bool may_combine_partial_sharding, bool allow_aggressive_resharding = false) { if (instruction->shape().IsTuple()) { if (auto new_sub_sharding = ReturnImprovedSubSharding( std::move(sharding), instruction, index, may_combine_partial_sharding, allow_aggressive_resharding)) { HloSharding new_sharding = instruction->has_sharding() ? instruction->sharding() : HloSharding::Single(instruction->shape(), HloSharding::Replicate()); ShapeTree<HloSharding> sharding_shape_tree = new_sharding.GetAsShapeTree(instruction->shape()); *sharding_shape_tree.mutable_element(index) = new_sub_sharding.value(); instruction->set_sharding(HloSharding::Tuple(sharding_shape_tree)); return true; } else { return false; } } CHECK(index.size() == 1 && index[0] == 0); return MaybeImproveInstructionSharding(std::move(sharding), instruction, may_combine_partial_sharding, allow_aggressive_resharding); } bool IsConvolutionKernelSmall(const HloInstruction* instruction) { CHECK_EQ(instruction->opcode(), HloOpcode::kConvolution); const HloInstruction* rhs = instruction->operand(1); const auto& dnums = instruction->convolution_dimension_numbers(); int64_t kernel_dim_prod = 1; int64_t output_dim_prod = 1; for (int64_t i = 0; i < dnums.input_spatial_dimensions().size(); ++i) { int64_t kernel_dim = rhs->shape().dimensions(dnums.kernel_spatial_dimensions(i)); kernel_dim_prod *= kernel_dim; int64_t output_dim = instruction->shape().dimensions(dnums.output_spatial_dimensions(i)); output_dim_prod *= output_dim; if (kernel_dim >= output_dim && (i < 2 || kernel_dim > 3 || kernel_dim_prod >= output_dim_prod)) { return false; } } return true; } bool IsPassthroughCustomOps(const HloInstruction* hlo) { if (hlo->IsCustomCall({"Sharding", "X64Combine", "LayoutConstraint"})) { return true; } if (hlo->operand_count() != 1 || !hlo->shape().IsArray() || !hlo->operand(0)->shape().IsArray() || hlo->operand(0)->shape().rank() != hlo->shape().rank()) { return false; } return hlo->IsCustomCall( {"ResizeNearest", "ResizeBilinear", "ResizeNearestGrad", "ResizeBilinearGrad", "Cholesky", host_memory_offload_annotations::kMoveToDeviceCustomCallTarget, host_memory_offload_annotations::kMoveToHostCustomCallTarget}); } const HloInstruction* PickRepresentativeOperand( const HloInstruction* instruction) { switch (instruction->opcode()) { case HloOpcode::kMap: case HloOpcode::kPad: case HloOpcode::kPower: case HloOpcode::kOptimizationBarrier: case HloOpcode::kReverse: case HloOpcode::kSlice: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: // For these opcodes the output sharding has to be determined by the // sharding of the first operand but we can only determine sharding based // on it if it already has a sharding. if (instruction->operand(0)->has_sharding()) { return instruction->operand(0); } return nullptr; case HloOpcode::kAbs: case HloOpcode::kAdd: case HloOpcode::kAnd: case HloOpcode::kAtan2: case HloOpcode::kBitcastConvert: case HloOpcode::kCeil: case HloOpcode::kClamp: case HloOpcode::kClz: case HloOpcode::kCompare: case HloOpcode::kComplex: case HloOpcode::kConcatenate: case HloOpcode::kConvert: case HloOpcode::kCopy: case HloOpcode::kCos: case HloOpcode::kAllGather: case HloOpcode::kAllReduce: case HloOpcode::kReduceScatter: case HloOpcode::kAllToAll: case HloOpcode::kCollectiveBroadcast: case HloOpcode::kCollectivePermute: case HloOpcode::kDivide: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kFloor: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kMultiply: case HloOpcode::kNegate: case HloOpcode::kNot: case HloOpcode::kOr: case HloOpcode::kPopulationCount: case HloOpcode::kReal: case HloOpcode::kReducePrecision: case HloOpcode::kRemainder: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kRsqrt: case HloOpcode::kSelect: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kTopK: case HloOpcode::kSort: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kSubtract: case HloOpcode::kStochasticConvert: case HloOpcode::kTan: case HloOpcode::kTanh: case HloOpcode::kWhile: case HloOpcode::kXor: { // For these opcodes the output sharding can be determined by any operand // so we find the operand with the most specific sharding. const HloInstruction* best_operand = nullptr; for (const HloInstruction* operand : instruction->operands()) { if (operand->has_sharding() && (best_operand == nullptr || hlo_sharding_util::IsShardingMoreSpecific( operand->sharding(), best_operand->sharding()))) { best_operand = operand; } } return best_operand; } case HloOpcode::kCustomCall: { if (IsPassthroughCustomOps(instruction)) { return instruction->operand(0); } return nullptr; } // There is no suitable operand for the rest of the opcodes. case HloOpcode::kAddDependency: case HloOpcode::kAfterAll: case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: case HloOpcode::kAllGatherStart: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduceStart: case HloOpcode::kAllReduceDone: case HloOpcode::kBatchNormGrad: case HloOpcode::kBatchNormInference: case HloOpcode::kBatchNormTraining: case HloOpcode::kBitcast: case HloOpcode::kBroadcast: case HloOpcode::kCall: case HloOpcode::kCholesky: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCollectivePermuteStart: case HloOpcode::kConditional: case HloOpcode::kConstant: case HloOpcode::kConvolution: case HloOpcode::kCopyDone: case HloOpcode::kCopyStart: case HloOpcode::kDomain: case HloOpcode::kDot: case HloOpcode::kDynamicSlice: case HloOpcode::kDynamicUpdateSlice: case HloOpcode::kDynamicReshape: case HloOpcode::kFft: case HloOpcode::kFusion: case HloOpcode::kGather: case HloOpcode::kGetTupleElement: case HloOpcode::kInfeed: case HloOpcode::kIota: case HloOpcode::kOutfeed: case HloOpcode::kParameter: case HloOpcode::kPartitionId: case HloOpcode::kRecv: case HloOpcode::kRecvDone: case HloOpcode::kReduce: case HloOpcode::kReduceWindow: case HloOpcode::kReplicaId: case HloOpcode::kReshape: case HloOpcode::kRng: case HloOpcode::kRngGetAndUpdateState: case HloOpcode::kRngBitGenerator: case HloOpcode::kScatter: case HloOpcode::kSelectAndScatter: case HloOpcode::kSend: case HloOpcode::kSendDone: case HloOpcode::kTranspose: case HloOpcode::kTriangularSolve: case HloOpcode::kTuple: case HloOpcode::kGetDimensionSize: case HloOpcode::kSetDimensionSize: return nullptr; } } bool SupportSpatialPartitioning( const HloInstruction* instruction, const ShardingPropagation::ComputationMap& computation_map, bool is_spmd, bool allow_spmd_sharding_propagation_to_output, bool allow_spmd_sharding_propagation_to_parameters, const CustomCallShardingHelper* sharding_helper) { const bool is_entry_root = instruction->parent() ->parent() ->entry_computation() ->root_instruction() == instruction; if (instruction->parent()->root_instruction() == instruction && computation_map.find(instruction->parent()) == computation_map.end() && !(is_entry_root && allow_spmd_sharding_propagation_to_output)) { // We don't support sharding the root instruction of a computation yet, // unless the computation is a while body. return false; } if (instruction->IsElementwise() && (instruction->opcode() != HloOpcode::kRng || is_spmd)) { return true; } switch (instruction->opcode()) { case HloOpcode::kBroadcast: case HloOpcode::kConcatenate: case HloOpcode::kConditional: case HloOpcode::kConstant: case HloOpcode::kConvolution: case HloOpcode::kOptimizationBarrier: case HloOpcode::kDot: case HloOpcode::kDynamicSlice: case HloOpcode::kDynamicUpdateSlice: case HloOpcode::kGather: case HloOpcode::kGetTupleElement: case HloOpcode::kInfeed: case HloOpcode::kIota: case HloOpcode::kPad: case HloOpcode::kReduceWindow: case HloOpcode::kReshape: case HloOpcode::kScatter: case HloOpcode::kSelectAndScatter: case HloOpcode::kSlice: case HloOpcode::kSort: case HloOpcode::kTranspose: case HloOpcode::kTuple: case HloOpcode::kWhile: case HloOpcode::kReduce: case HloOpcode::kRngBitGenerator: case HloOpcode::kAllReduce: case HloOpcode::kReduceScatter: return true; case HloOpcode::kParameter: return allow_spmd_sharding_propagation_to_parameters || computation_map.find(instruction->parent()) != computation_map.end(); case HloOpcode::kReverse: return is_spmd; case HloOpcode::kCustomCall: if (!is_spmd) { return false; } if (auto* partitioner = GetCustomCallPartitioner(instruction->custom_call_target())) { return partitioner->IsCustomCallShardable(instruction); } return (IsPassthroughCustomOps(instruction) || sharding_helper->IsCustomCallShardable(instruction)); default: return false; } } std::optional<HloSharding> LookaheadUserSharding(HloInstruction* instr, bool is_spmd, const CallGraph& call_graph) { if (instr->user_count() != 1) { return std::nullopt; } HloInstruction* current_user = instr->users()[0]; std::optional<HloSharding> sharding; std::vector<HloInstruction*> users_chain = {instr, current_user}; // Collect single user instructions along the way. while (!current_user->has_sharding()) { // Only consider single user chains. if (current_user->users().size() != 1) { users_chain.clear(); break; } current_user = current_user->users()[0]; users_chain.push_back(current_user); } // Early exit for unsupported cases. if (users_chain.empty()) { return std::nullopt; } for (int i = users_chain.size() - 1; i >= 1; --i) { HloInstruction* user = users_chain[i]; HloInstruction* current = users_chain[i - 1]; CHECK(user->has_sharding()); sharding = ShardingPropagation::GetShardingFromUser( *current, *user, INT64_MAX, is_spmd, call_graph, /*sharding_helper=*/nullptr); // We need to set the sharding to the instruction, because // GetShardingFromUser() interface uses sharding from the instruction // itself. It will be cleared out later. if (sharding.has_value() && i != 1) { current->set_sharding(*sharding); continue; } break; } // Clear the sharding of the middle instructions we set the sharding of // because they were unsharded. for (int i = 1; i < users_chain.size() - 1; ++i) { users_chain[i]->clear_sharding(); } return sharding; } bool InferGatherParallelShardingFromOperands( HloInstruction* instruction, const hlo_sharding_util::GatherScatterParallelDims& parallel_dims, bool may_combine_partial_sharding) { CHECK(DynCast<HloGatherInstruction>(instruction)); bool changed = false; auto aligned_operand_parallel_dims = hlo_sharding_util::IndexAlignedOperandParallelDims(parallel_dims); auto output_parallel_dims = hlo_sharding_util::GetGatherParallelOutputDims( *instruction, parallel_dims); // Infer output sharding from scatter operand sharding. if (hlo_sharding_util::IsSpatiallyPartitioned(instruction->operand(0))) { changed |= MaybeImproveInstructionSharding( hlo_sharding_util:: InferGatherScatterParallelShardingFromOperandSharding( instruction->operand(0)->sharding(), instruction->operand(0)->shape(), instruction->shape(), absl::MakeConstSpan(aligned_operand_parallel_dims), absl::MakeConstSpan(output_parallel_dims)), instruction, may_combine_partial_sharding); } // Infer output sharding from scatter indices sharding. if (hlo_sharding_util::IsSpatiallyPartitioned(instruction->operand(1))) { changed |= MaybeImproveInstructionSharding( hlo_sharding_util:: InferGatherScatterParallelShardingFromOperandSharding( instruction->operand(1)->sharding(), instruction->operand(1)->shape(), instruction->shape(), absl::MakeConstSpan(parallel_dims.indices_parallel_dims), absl::MakeConstSpan(output_parallel_dims)), instruction, may_combine_partial_sharding); } return changed; } bool InferScatterParallelShardingFromOperands( HloInstruction* instruction, const hlo_sharding_util::GatherScatterParallelDims& parallel_dims, bool may_combine_partial_sharding) { HloScatterInstruction* scatter = DynCast<HloScatterInstruction>(instruction); CHECK(scatter); const int64_t operand_count = scatter->scatter_operand_count(); auto scatter_operands = scatter->scatter_operands(); auto scatter_indices = scatter->scatter_indices(); auto scatter_updates = scatter->scatter_updates(); bool changed = false; auto aligned_operand_parallel_dims = hlo_sharding_util::IndexAlignedOperandParallelDims(parallel_dims); auto update_parallel_dims = hlo_sharding_util::GetScatterParallelUpdateDims( *instruction, parallel_dims); auto output_parallel_dims = aligned_operand_parallel_dims; // Infer output sharding from scatter operand sharding. Shape shape = operand_count == 1 ? instruction->shape() : ShapeUtil::GetSubshape(instruction->shape(), {0}); for (int64_t i = 0; i != operand_count; ++i) { if (hlo_sharding_util::IsSpatiallyPartitioned(scatter_operands[i])) { changed |= MaybeImproveInstructionSubSharding( hlo_sharding_util:: InferGatherScatterParallelShardingFromOperandSharding( scatter_operands[i]->sharding(), scatter_operands[i]->shape(), shape, absl::MakeConstSpan(aligned_operand_parallel_dims), absl::MakeConstSpan(output_parallel_dims)), instruction, {i}, may_combine_partial_sharding); } } // Infer output sharding from scatter indices sharding. if (hlo_sharding_util::IsSpatiallyPartitioned(scatter_indices)) { auto parallel_sharding_from_indices = hlo_sharding_util:: InferGatherScatterParallelShardingFromOperandSharding( scatter_indices->sharding(), scatter_indices->shape(), shape, absl::MakeConstSpan(parallel_dims.indices_parallel_dims), absl::MakeConstSpan(output_parallel_dims)); for (int64_t i = 0; i != operand_count; ++i) { changed |= MaybeImproveInstructionSubSharding( parallel_sharding_from_indices, instruction, {i}, may_combine_partial_sharding); } } // Infer output sharding from scatter update sharding. for (int64_t i = 0; i != operand_count; ++i) { if (hlo_sharding_util::IsSpatiallyPartitioned(scatter_updates[i])) { changed |= MaybeImproveInstructionSubSharding( hlo_sharding_util:: InferGatherScatterParallelShardingFromOperandSharding( scatter_updates[i]->sharding(), scatter_updates[i]->shape(), shape, absl::MakeConstSpan(update_parallel_dims), absl::MakeConstSpan(output_parallel_dims)), instruction, {i}, may_combine_partial_sharding); } } return changed; } bool CanPropagateThroughAtAggressiveLevel(const HloInstruction& inst, int64_t aggressiveness) { // At minimum aggressiveness, only allow pass-through ops. if (aggressiveness < 1 && !(inst.IsElementwise() || inst.IsCustomCall("Sharding")) && inst.opcode() != HloOpcode::kTranspose && inst.opcode() != HloOpcode::kReshape && inst.opcode() != HloOpcode::kTuple && inst.opcode() != HloOpcode::kGetTupleElement && inst.opcode() != HloOpcode::kWhile && inst.opcode() != HloOpcode::kDynamicSlice && inst.opcode() != HloOpcode::kDynamicUpdateSlice && inst.opcode() != HloOpcode::kOptimizationBarrier && inst.opcode() != HloOpcode::kConcatenate && inst.opcode() != HloOpcode::kCall && inst.opcode() != HloOpcode::kCopy) { return false; } // Broadcast propagation should have at least aggressiveness 2. if (aggressiveness < 2 && inst.opcode() == HloOpcode::kBroadcast) { return false; } return true; } bool SameShardingMetadata(const HloSharding& a, const HloSharding& b) { DCHECK_EQ(a, b); auto same_metadata = [](absl::Span<const OpMetadata> a, absl::Span<const OpMetadata> b) { if (a.size() != b.size()) return false; for (int i = 0, e = a.size(); i < e; ++i) { if (!protobuf_util::ProtobufEquals(a[i], b[i])) { return false; } } return true; }; if (a.IsTuple()) { for (int i = 0, e = a.tuple_elements().size(); i < e; ++i) { if (!same_metadata(a.tuple_elements()[i].metadata(), b.tuple_elements()[i].metadata())) { return false; } } return true; } else { return same_metadata(a.metadata(), b.metadata()); } } auto same_metadata = [](absl::Span<const OpMetadata> a, absl::Span<const OpMetadata> b) { if (a.size() != b.size()) return false; for (int i = 0, e = a.size(); i < e; ++i) { if (!protobuf_util::ProtobufEquals(a[i], b[i])) { return false; } } return true; }; bool AssignShardingMetadata( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { bool changed = false; for (HloComputation* computation : module->computations(execution_threads)) { for (HloInstruction* instruction : computation->instructions()) { const auto& metadata = instruction->metadata(); if (!instruction->has_sharding() || metadata.ByteSizeLong() == 0) { continue; } HloSharding sharding_with_metadata = instruction->sharding().WithMetadata({metadata}, /*overwrite=*/false); if (!SameShardingMetadata(instruction->sharding(), sharding_with_metadata)) { instruction->set_sharding(std::move(sharding_with_metadata)); changed = true; } } } return changed; } bool RemoveShardingMetadata( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { bool changed = false; for (HloComputation* computation : module->computations(execution_threads)) { for (HloInstruction* instruction : computation->instructions()) { if (!instruction->has_sharding()) { continue; } HloSharding sharding_no_metadata = instruction->sharding().WithoutMetadata(); if (!SameShardingMetadata(instruction->sharding(), sharding_no_metadata)) { instruction->set_sharding(std::move(sharding_no_metadata)); changed = true; } } } return changed; } absl::Status CheckAndUpdateDeviceAssignmentsInWhileBody( HloInstruction* while_instruction) { auto bad_status = [](HloInstruction* instruction, int64_t device, HloInstruction* channel_instruction, int64_t correct_device) { return FailedPrecondition( "Instruction: %s is on device: %d, which conflicts with device: %d " "of channel instruction: %s", instruction->name(), device, correct_device, channel_instruction->name()); }; CHECK_EQ(while_instruction->opcode(), HloOpcode::kWhile); HloComputation* while_body = while_instruction->while_body(); // Maps a device number to an instruction in the while_body with that // device assignment. std::map<int64_t, HloInstruction*> devices_to_instructions; std::optional<int64_t> unique_device = std::nullopt; HloInstruction* channel_instruction = nullptr; for (HloInstruction* instruction : while_body->instructions()) { if (instruction->sharding_unique_device()) { auto opcode = instruction->opcode(); int64_t device = *instruction->sharding_unique_device(); if (unique_device.has_value()) { if (*unique_device != device) { return bad_status(instruction, device, channel_instruction, *unique_device); } } else if (((opcode == HloOpcode::kSend || opcode == HloOpcode::kRecv) && !Cast<HloSendRecvInstruction>(instruction) ->is_host_transfer()) // Cross-replica AllReduces don't have a channel_id, and we // don't enforce any invariant about their device assignment. || ((opcode == HloOpcode::kAllReduce || opcode == HloOpcode::kReduceScatter) && instruction->channel_id())) { channel_instruction = instruction; unique_device = device; if (!devices_to_instructions.empty()) { for (auto it = devices_to_instructions.begin(); it != devices_to_instructions.end(); ++it) { if (*unique_device != it->first) { return bad_status(it->second, it->first, channel_instruction, *unique_device); } } } } else { devices_to_instructions[device] = instruction; } } } if (unique_device.has_value()) { auto while_device = while_instruction->sharding_unique_device(); if (while_device.has_value() && *unique_device != *while_device) { return bad_status(while_instruction, *while_device, channel_instruction, *unique_device); } auto body_root = while_body->root_instruction(); auto root_device = body_root->sharding_unique_device(); if (!root_device.has_value()) { body_root->set_device_sharding(*unique_device); } else if (*unique_device != *root_device) { return bad_status(body_root, *root_device, channel_instruction, *unique_device); } } return absl::OkStatus(); } auto bad_status = [](HloInstruction* instruction, int64_t device, HloInstruction* channel_instruction, int64_t correct_device) { return FailedPrecondition( "Instruction: %s is on device: %d, which conflicts with device: %d " "of channel instruction: %s", instruction->name(), device, correct_device, channel_instruction->name()); }; bool RefineManualAutoShardingFromAuto( const HloSharding& to_merge, absl::Span<const int64_t> unspecified_dims, HloSharding* auto_sharding, HloSharding* manual_sharding) { if (!manual_sharding->IsManualSubgroup() || auto_sharding->IsManualSubgroup() || !manual_sharding->HasPartialReplication() || manual_sharding->subgroup_types().size() != 2) { // We do not support nested subgroup manual. man_conversion_op must have // replication in order to be merged. return false; } HloSharding partial_rep = hlo_sharding_util::PartiallyReplicateTiledShardingOnAllDimsExcept( to_merge, unspecified_dims); if (partial_rep.IsTileMaximal()) { return false; } // Merge with the non-manual partial annotation. if (!hlo_sharding_util::MergeShardingIfCompatible( partial_rep, auto_sharding->NumTiles() + 1, auto_sharding)) { return false; } // Merge with the manual partial annotation. const int64_t data_rank = partial_rep.TiledDataRank(); // We are also merging the non-manual sharding into the manual sharding. To // leverage existing merging implementation, we treat the manual dim as a // data dim, and add it right before the replication dim. std::vector<int64_t> partial_manual_shape( partial_rep.tile_assignment().dimensions().begin(), partial_rep.tile_assignment().dimensions().end()); partial_manual_shape.insert(partial_manual_shape.begin() + data_rank, 1); auto partial_tiling_for_manual = partial_rep.tile_assignment().Reshape(partial_manual_shape); HloSharding partial_rep_for_manual = HloSharding::PartialTile( partial_tiling_for_manual, partial_rep.metadata()); auto man_tiling = manual_sharding->tile_assignment(); if (manual_sharding->subgroup_types().back() != OpSharding::REPLICATED) { // Move the manual dim before replication dim. std::vector<int> transposed_dims(man_tiling.num_dimensions()); absl::c_iota(transposed_dims, 0); std::swap(transposed_dims.back(), transposed_dims[data_rank]); man_tiling = man_tiling.Transpose(transposed_dims); } HloSharding tmp_sharding_for_merging = HloSharding::PartialTile( std::move(man_tiling), manual_sharding->metadata()); if (!hlo_sharding_util::MergeShardingIfCompatible( partial_rep_for_manual, tmp_sharding_for_merging.NumTiles() + 1, &tmp_sharding_for_merging)) { return false; } std::vector<OpSharding::Type> subgroup_types; subgroup_types.push_back(OpSharding::MANUAL); if (tmp_sharding_for_merging.HasPartialReplication()) { subgroup_types.push_back(OpSharding::REPLICATED); } *manual_sharding = HloSharding::Subgroup( tmp_sharding_for_merging.tile_assignment(), subgroup_types, tmp_sharding_for_merging.metadata()); return true; } bool RefineManualAutoShardingFromManual( const HloSharding& to_merge, absl::Span<const int64_t> unspecified_dims, HloSharding* auto_sharding, HloSharding* manual_sharding) { if (!to_merge.IsManualSubgroup() || !manual_sharding->IsManualSubgroup() || !manual_sharding->HasPartialReplication() || auto_sharding->IsManualSubgroup() || manual_sharding->subgroup_types().size() != 2) { return false; } HloSharding partial_rep = hlo_sharding_util::PartiallyReplicateTiledShardingOnAllDimsExcept( to_merge, unspecified_dims); if (partial_rep.IsTileMaximal()) { return false; } if (!hlo_sharding_util::MergeShardingIfCompatible( partial_rep, manual_sharding->NumTiles() + 1, manual_sharding)) { return false; } HloSharding partial_rep_for_auto = HloSharding::Subgroup( partial_rep.tile_assignment(), std::vector<OpSharding::Type>(partial_rep.subgroup_types().size(), OpSharding::REPLICATED), partial_rep.metadata()); if (!hlo_sharding_util::MergeShardingIfCompatible( partial_rep_for_auto, auto_sharding->NumTiles() + 1, auto_sharding)) { return false; } return true; } bool InferUnspecifiedDimsFromOperand(HloInstruction* annotate_op, absl::Span<const int64_t> unspecified_dims, HloInstruction** man_conversion_op_after) { // ProcessShardingInstruction will either keep the "Sharding" custom call as // is or replace it with a copy. CHECK(annotate_op->IsCustomCall("Sharding") || annotate_op->opcode() == HloOpcode::kCopy); if (!hlo_sharding_util::IsSpatiallyPartitioned(annotate_op->operand(0))) { return false; } const HloSharding& operand_sharding = annotate_op->operand(0)->sharding(); if (!operand_sharding.IsTiled()) { return false; } HloInstruction* man_conversion_op = nullptr; if (annotate_op->user_count() == 1) { HloInstruction* user = annotate_op->users()[0]; if (user->IsCustomCall("SPMDFullToShardShape") || user->IsCustomCall("SPMDShardToFullShape")) { std::vector<int64_t> user_unspec_dims; if (!sharding_op_util::ParseAttributes( Cast<HloCustomCallInstruction>(user)->opaque(), &user_unspec_dims) .ok()) { return false; } absl::c_sort(user_unspec_dims); if (unspecified_dims != user_unspec_dims) { // The manual/auto conversion op must have the same set of unspecified // dims. return false; } man_conversion_op = user; } } *man_conversion_op_after = man_conversion_op; if (man_conversion_op == nullptr) { HloSharding partial_replicated = hlo_sharding_util::PartiallyReplicateTiledShardingOnAllDimsExcept( operand_sharding, unspecified_dims); HloSharding sharding = annotate_op->sharding(); if (!hlo_sharding_util::MergeShardingIfCompatible( partial_replicated, sharding.NumTiles() + 1, &sharding)) { return false; } annotate_op->set_sharding(sharding); return true; } if (man_conversion_op->IsCustomCall("SPMDFullToShardShape")) { HloSharding auto_sharding = annotate_op->sharding(); HloSharding manual_sharding = man_conversion_op->sharding(); if (!RefineManualAutoShardingFromAuto(operand_sharding, unspecified_dims, &auto_sharding, &manual_sharding)) { return false; } annotate_op->set_sharding(auto_sharding); man_conversion_op->set_sharding(manual_sharding); return true; } CHECK(man_conversion_op->IsCustomCall("SPMDShardToFullShape")); HloSharding manual_sharding = annotate_op->sharding(); HloSharding auto_sharding = man_conversion_op->sharding(); if (!RefineManualAutoShardingFromManual(operand_sharding, unspecified_dims, &auto_sharding, &manual_sharding)) { return false; } annotate_op->set_sharding(manual_sharding); man_conversion_op->set_sharding(auto_sharding); return true; } bool InferUnspecifiedDimsFromOneUser(HloInstruction* annotate_op, const HloInstruction* user, int64_t aggressiveness, bool is_spmd, absl::Span<const int64_t> unspecified_dims, HloInstruction* man_conversion_op, const CallGraph& call_graph) { CHECK(annotate_op->IsCustomCall("Sharding") || annotate_op->opcode() == HloOpcode::kCopy); if (!user->has_sharding() || !user->sharding().IsTiled()) { return false; } std::optional<HloSharding> user_sharding = ShardingPropagation::GetShardingFromUser( man_conversion_op == nullptr ? *annotate_op : *man_conversion_op, *user, aggressiveness, is_spmd, call_graph, /*sharding_helper=*/nullptr); if (!user_sharding.has_value() || user_sharding->IsTileMaximal()) { return false; } if (man_conversion_op == nullptr) { HloSharding partial_replicated = hlo_sharding_util::PartiallyReplicateTiledShardingOnAllDimsExcept( *user_sharding, unspecified_dims); HloSharding sharding = annotate_op->sharding(); if (!hlo_sharding_util::MergeShardingIfCompatible( partial_replicated, sharding.NumTiles() + 1, &sharding)) { return false; } annotate_op->set_sharding(sharding); return true; } if (man_conversion_op->IsCustomCall("SPMDFullToShardShape")) { HloSharding auto_sharding = annotate_op->sharding(); HloSharding manual_sharding = man_conversion_op->sharding(); if (!RefineManualAutoShardingFromManual(*user_sharding, unspecified_dims, &auto_sharding, &manual_sharding)) { return false; } annotate_op->set_sharding(auto_sharding); man_conversion_op->set_sharding(manual_sharding); return true; } CHECK(man_conversion_op->IsCustomCall("SPMDShardToFullShape")); HloSharding manual_sharding = annotate_op->sharding(); HloSharding auto_sharding = man_conversion_op->sharding(); if (!RefineManualAutoShardingFromAuto(*user_sharding, unspecified_dims, &auto_sharding, &manual_sharding)) { return false; } annotate_op->set_sharding(manual_sharding); man_conversion_op->set_sharding(auto_sharding); return true; } bool InferUnspecifiedDimsFromUsers(HloInstruction* annotate_op, absl::Span<const int64_t> unspecified_dims, int64_t aggressiveness, bool is_spmd, HloInstruction** man_conversion_op_after, const CallGraph& call_graph) { HloInstruction* man_conversion_op = nullptr; if (annotate_op->user_count() == 1) { HloInstruction* user = annotate_op->users()[0]; if (user->IsCustomCall("SPMDFullToShardShape") || user->IsCustomCall("SPMDShardToFullShape")) { std::vector<int64_t> user_unspec_dims; absl::c_sort(user_unspec_dims); if (!sharding_op_util::ParseAttributes( Cast<HloCustomCallInstruction>(user)->opaque(), &user_unspec_dims) .ok() || unspecified_dims != user_unspec_dims) { // The manual/auto conversion op must have the same set of unspecified // dims. return false; } man_conversion_op = user; } } *man_conversion_op_after = man_conversion_op; HloInstruction* op_for_users = man_conversion_op == nullptr ? annotate_op : man_conversion_op; bool changed = false; for (HloInstruction* user : op_for_users->users()) { changed |= InferUnspecifiedDimsFromOneUser( annotate_op, user, aggressiveness, is_spmd, unspecified_dims, man_conversion_op, call_graph); } return changed; } bool InferUnspecifiedDimsFromShardGroup( HloInstruction* annotate_op, absl::Span<const int64_t> unspecified_dims, const absl::flat_hash_set<HloInstruction*>& shard_group) { // ProcessShardingInstruction will either keep the "Sharding" custom call as // is or replace it with a copy. CHECK(annotate_op->IsCustomCall("Sharding") || annotate_op->opcode() == HloOpcode::kCopy); // Do not propagate sharding to ShardBarrierTo custom-call. if (annotate_op->IsCustomCall(spmd::kShardBarrierTo)) { return false; } bool changed = false; for (const HloInstruction* member : shard_group) { if (member == annotate_op) { continue; } // Do not propagate sharding from ShardBarrierFrom custom-call. if (member->IsCustomCall(spmd::kShardBarrierFrom)) { continue; } if (!hlo_sharding_util::IsSpatiallyPartitioned(member)) { continue; } const HloSharding& member_sharding = member->sharding(); if (!member_sharding.IsTiled()) { continue; } HloSharding partial_replicated = hlo_sharding_util::PartiallyReplicateTiledShardingOnAllDimsExcept( member_sharding, unspecified_dims); HloSharding sharding = annotate_op->sharding(); if (!hlo_sharding_util::MergeShardingIfCompatible( partial_replicated, sharding.NumTiles() + 1, &sharding)) { continue; } annotate_op->set_sharding(sharding); changed |= true; } return changed; } bool IsCSEPreventionTarget(const HloInstruction* instruction) { // Scalar broadcasts are the most common CSE target that causes cross-layer // propagation on unrelated subgraphs. return instruction->opcode() == HloOpcode::kBroadcast && instruction->operand(0)->shape().rank() == 0; } HloSharding SetCSEPreventionSharding(const HloSharding& sharding) { OpMetadata metadata; metadata.set_op_name("_sharding_propagation_cse_prevention"); return sharding.WithMetadata({metadata}, /*overwrite=*/true); } bool IsCSEPreventionSharding(const HloSharding& sharding) { if (sharding.metadata().size() != 1) { return false; } return sharding.metadata()[0].op_name() == "_sharding_propagation_cse_prevention"; } bool InferDotShardingFromOperands( HloInstruction* instruction, const CallGraph& call_graph, const dot_as_convolution_util::DotConvolutionDimsInfo& dnums, bool may_combine_partial_sharding, bool is_spmd) { auto from_operand = [&](int64_t operand_index) { auto operand = instruction->operand(operand_index); const HloSharding& operand_sharding = operand->sharding(); if (operand_sharding.IsTileMaximal()) { return operand_sharding; } std::vector<int64_t> contracting_dims; contracting_dims.reserve(dnums.contracting_dims.size()); for (const auto& dim : dnums.contracting_dims) { contracting_dims.push_back(operand_index == 0 ? dim.lhs : dim.rhs); } // It's possible that some size-1 spatial dims of convolutions are parsed as // non-contracting dims. We might have tiled dimensions on them. for (const auto& dim : operand_index == 0 ? dnums.rhs_non_contracting_dims : dnums.lhs_non_contracting_dims) { int64_t d = operand_index == 0 ? dim.lhs : dim.rhs; if (d >= 0) { contracting_dims.push_back(d); } } auto replicate_contracting_dims = hlo_sharding_util::PartiallyReplicateTiledShardingOnDims( operand_sharding, contracting_dims); std::vector<int64_t> out_dims_to_op_perm(instruction->shape().rank(), -1); std::vector<int64_t> op_dims_to_output_perm(operand->shape().rank(), -1); for (const auto& dim : dnums.batch_dims) { out_dims_to_op_perm[dim.output] = operand_index == 0 ? dim.lhs : dim.rhs; op_dims_to_output_perm[operand_index == 0 ? dim.lhs : dim.rhs] = dim.output; } for (const auto& dim : operand_index == 0 ? dnums.lhs_non_contracting_dims : dnums.rhs_non_contracting_dims) { out_dims_to_op_perm[dim.output] = operand_index == 0 ? dim.lhs : dim.rhs; op_dims_to_output_perm[operand_index == 0 ? dim.lhs : dim.rhs] = dim.output; } return *hlo_sharding_util::TransposeShardingWithCollapsedDims( replicate_contracting_dims, op_dims_to_output_perm, out_dims_to_op_perm); }; std::optional<HloSharding> improved_operand_0; std::optional<HloSharding> improved_operand_1; if (hlo_sharding_util::IsSpatiallyPartitioned(instruction->operand(0))) { improved_operand_0 = ReturnImprovedSharding( from_operand(0), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/false); } if (hlo_sharding_util::IsSpatiallyPartitioned(instruction->operand(1))) { improved_operand_1 = ReturnImprovedSharding( from_operand(1), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/false); } // If not improved sharding found then do not set any sharding. if (!improved_operand_0.has_value() && !improved_operand_1.has_value()) { return false; } // Sharding found from operand 0 but not operand 1. Set sharding from operand // 0 if (improved_operand_0.has_value() && !improved_operand_1.has_value()) { instruction->set_sharding(*improved_operand_0); return true; } // Sharding found from operand 1 but not operand 0. Set sharding from operand // 1 if (!improved_operand_0.has_value() && improved_operand_1.has_value()) { instruction->set_sharding(*improved_operand_1); return true; } CHECK(improved_operand_0.has_value() && improved_operand_1.has_value()); std::optional<HloSharding> lookahead_sharding = LookaheadUserSharding(instruction, is_spmd, call_graph); std::array<HloSharding, 2> sharding_priority = {*improved_operand_0, *improved_operand_1}; bool priority_defined_with_lookahead = false; // Found sharding from lookahead. if (lookahead_sharding.has_value()) { const bool operand_0_is_lookahead_subtiling = hlo_sharding_util::IsSubTilingOrEqualSharding( instruction->shape(), *lookahead_sharding, *improved_operand_0); const bool operand_1_is_lookahead_subtiling = hlo_sharding_util::IsSubTilingOrEqualSharding( instruction->shape(), *lookahead_sharding, *improved_operand_1); // If the sharding from operand 0 is a subtiling of the user, but not the // one from operand 1 prioritize that sharding. if (operand_0_is_lookahead_subtiling && !operand_1_is_lookahead_subtiling) { priority_defined_with_lookahead = true; } // If the sharding from operand 1 is a subtiling of the user, but not the // one from operand 0 prioritize that sharding. if (!operand_0_is_lookahead_subtiling && operand_1_is_lookahead_subtiling) { instruction->set_sharding(*improved_operand_1); std::swap(sharding_priority[0], sharding_priority[1]); priority_defined_with_lookahead = true; } } // If lookahead didn't define a priority then use size. if (!priority_defined_with_lookahead && ShapeUtil::ByteSizeOf(instruction->operand(0)->shape()) < ShapeUtil::ByteSizeOf(instruction->operand(1)->shape())) { std::swap(sharding_priority[0], sharding_priority[1]); } // Set primary sharding to the instruction and then try to improve it with // the secondary sharding. instruction->set_sharding(sharding_priority[0]); MaybeImproveInstructionSharding(sharding_priority[1], instruction, may_combine_partial_sharding); return true; } auto from_operand = [&](int64_t operand_index) { auto operand = instruction->operand(operand_index); const HloSharding& operand_sharding = operand->sharding(); if (operand_sharding.IsTileMaximal()) { return operand_sharding; } std::vector<int64_t> contracting_dims; contracting_dims.reserve(dnums.contracting_dims.size()); for (const auto& dim : dnums.contracting_dims) { contracting_dims.push_back(operand_index == 0 ? dim.lhs : dim.rhs); } // It's possible that some size-1 spatial dims of convolutions are parsed as // non-contracting dims. We might have tiled dimensions on them. for (const auto& dim : operand_index == 0 ? dnums.rhs_non_contracting_dims : dnums.lhs_non_contracting_dims) { int64_t d = operand_index == 0 ? dim.lhs : dim.rhs; if (d >= 0) { contracting_dims.push_back(d); } } auto replicate_contracting_dims = hlo_sharding_util::PartiallyReplicateTiledShardingOnDims( operand_sharding, contracting_dims); std::vector<int64_t> out_dims_to_op_perm(instruction->shape().rank(), -1); std::vector<int64_t> op_dims_to_output_perm(operand->shape().rank(), -1); for (const auto& dim : dnums.batch_dims) { out_dims_to_op_perm[dim.output] = operand_index == 0 ? dim.lhs : dim.rhs; op_dims_to_output_perm[operand_index == 0 ? dim.lhs : dim.rhs] = dim.output; } for (const auto& dim : operand_index == 0 ? dnums.lhs_non_contracting_dims : dnums.rhs_non_contracting_dims) { out_dims_to_op_perm[dim.output] = operand_index == 0 ? dim.lhs : dim.rhs; op_dims_to_output_perm[operand_index == 0 ? dim.lhs : dim.rhs] = dim.output; } return *hlo_sharding_util::TransposeShardingWithCollapsedDims( replicate_contracting_dims, op_dims_to_output_perm, out_dims_to_op_perm); }; bool InferConvolutionShardingFromOperands(HloInstruction* instruction, const CallGraph& call_graph, int64_t aggressiveness, bool may_combine_partial_sharding, bool is_spmd) { auto get_partitions_for_dims = [&](const HloInstruction* inst, absl::Span< const dot_as_convolution_util::DotConvolutionDimsInfo::DimNums> dims, int lhs_or_rhs) { int64_t partitions = 1; if (!inst->has_sharding()) { return partitions; } const auto& sharding = inst->sharding(); if (sharding.IsTileMaximal()) { return partitions; } for (const auto& dim : dims) { if (lhs_or_rhs == 0) { partitions *= sharding.tile_assignment().dim(dim.lhs); } else { CHECK_EQ(lhs_or_rhs, 1); partitions *= sharding.tile_assignment().dim(dim.rhs); } } return partitions; }; auto dot_dims = dot_as_convolution_util::ParseConvolutionDimsInfo(instruction); const int64_t lhs_conv_spatial_partitions = get_partitions_for_dims( instruction->operand(0), dot_dims.conv_spatial_dims, 0); const int64_t rhs_conv_spatial_partitions = get_partitions_for_dims( instruction->operand(1), dot_dims.conv_spatial_dims, 1); if (dot_dims.conv_spatial_dims.empty() || (lhs_conv_spatial_partitions == 1 && rhs_conv_spatial_partitions == 1 && instruction->batch_group_count() == 1 && instruction->feature_group_count() == 1)) { return InferDotShardingFromOperands(instruction, call_graph, dot_dims, may_combine_partial_sharding, is_spmd); } const auto& dnums = instruction->convolution_dimension_numbers(); const HloInstruction* lhs = instruction->operand(0); auto get_tiled_sharding_based_on_lhs = [&] { CHECK(!lhs->sharding().IsTileMaximal()); std::vector<int64_t> output_to_lhs_indices(instruction->shape().rank()); output_to_lhs_indices[dnums.output_batch_dimension()] = dnums.input_batch_dimension(); output_to_lhs_indices[dnums.output_feature_dimension()] = dnums.input_feature_dimension(); for (int64_t i = 0; i < dnums.input_spatial_dimensions_size(); ++i) { output_to_lhs_indices[dnums.output_spatial_dimensions(i)] = dnums.input_spatial_dimensions(i); } return hlo_sharding_util::TransposeSharding(lhs->sharding(), output_to_lhs_indices); }; if (!hlo_sharding_util::IsSpatiallyPartitioned(lhs)) { return false; } if (lhs->sharding().IsTileMaximal()) { return MaybeImproveInstructionSharding(lhs->sharding(), instruction, may_combine_partial_sharding); } if (IsConvolutionKernelSmall(instruction)) { // If the kernel is small compared to the input then we can generate an // output what is sharded the same way as the input. const auto& tile_assignment = lhs->sharding().tile_assignment(); if (tile_assignment.dim(dnums.input_feature_dimension()) > 1) { return false; } return MaybeImproveInstructionSharding(get_tiled_sharding_based_on_lhs(), instruction, may_combine_partial_sharding); } // If the kernel is large (e.g., backward convolution) then we only support // replicated output. We intend to keep the sharding along the batch dimension // between lhs and output. return MaybeImproveInstructionSharding( hlo_sharding_util::PartiallyReplicateTiledShardingOnAllDimsExcept( lhs->sharding(), {dnums.input_batch_dimension()}), instruction, may_combine_partial_sharding); } [&](const HloInstruction* inst, absl::Span< const dot_as_convolution_util::DotConvolutionDimsInfo::DimNums> dims, int lhs_or_rhs) { int64_t partitions = 1; if (!inst->has_sharding()) { return partitions; } const auto& sharding = inst->sharding(); if (sharding.IsTileMaximal()) { return partitions; } for (const auto& dim : dims) { if (lhs_or_rhs == 0) { partitions *= sharding.tile_assignment().dim(dim.lhs); } else { CHECK_EQ(lhs_or_rhs, 1); partitions *= sharding.tile_assignment().dim(dim.rhs); } } return partitions; }; auto get_tiled_sharding_based_on_lhs = [&] { CHECK(!lhs->sharding().IsTileMaximal()); std::vector<int64_t> output_to_lhs_indices(instruction->shape().rank()); output_to_lhs_indices[dnums.output_batch_dimension()] = dnums.input_batch_dimension(); output_to_lhs_indices[dnums.output_feature_dimension()] = dnums.input_feature_dimension(); for (int64_t i = 0; i < dnums.input_spatial_dimensions_size(); ++i) { output_to_lhs_indices[dnums.output_spatial_dimensions(i)] = dnums.input_spatial_dimensions(i); } return hlo_sharding_util::TransposeSharding(lhs->sharding(), output_to_lhs_indices); }; std::optional<HloSharding> InferBroadcastOperandSharding( const HloInstruction& instruction, bool is_spmd) { if (instruction.sharding().IsReplicated() || instruction.sharding().IsManual()) { return instruction.sharding(); } std::vector<int64_t> dims_to_replicate; bool needs_replication = false; for (int64_t i = 0; i < instruction.shape().rank(); ++i) { if (absl::c_count(instruction.dimensions(), i) == 0) { dims_to_replicate.push_back(i); if (instruction.sharding().tile_assignment().dim(i) > 1) { needs_replication = true; } } } // If not SPMD, only support when none of the partitioned dimensions in // the broadcast output belong to new dimensions. if (!is_spmd && needs_replication) { return std::nullopt; } return hlo_sharding_util::RemoveShapeDimensions( hlo_sharding_util::PartiallyReplicateTiledShardingOnDims( instruction.sharding(), dims_to_replicate), dims_to_replicate); } bool InferReduceShardingFromOperand(HloInstruction* instruction, bool may_combine_partial_sharding, bool is_spmd) { auto get_maybe_tuple_sharding = [&](HloSharding sharding) { if (instruction->shape().IsArray()) { return sharding; } std::vector<HloSharding> tuple(instruction->shape().tuple_shapes_size(), std::move(sharding)); return HloSharding::Tuple(instruction->shape(), tuple); }; auto* reduce = Cast<HloReduceInstruction>(instruction); bool changed = false; for (HloInstruction* operand : reduce->inputs()) { if (!hlo_sharding_util::IsSpatiallyPartitioned(operand)) { continue; } if (operand->sharding().IsReplicated() || (!is_spmd && absl::c_any_of(instruction->dimensions(), [operand](int64_t dim) { return operand->sharding().tile_assignment().dim(dim) > 1; }))) { // We are reducing along one of the sharded dimensions. We only // support this in SPMD. changed |= MaybeImproveInstructionSharding( get_maybe_tuple_sharding( hlo_sharding_util::ReplicateAllDataDims(operand->sharding())), reduce, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); continue; } auto after_partial_replication = operand->sharding().IsReplicated() ? operand->sharding() : hlo_sharding_util::PartiallyReplicateTiledShardingOnDims( operand->sharding(), reduce->dimensions()); if (after_partial_replication.IsReplicated()) { changed |= MaybeImproveInstructionSharding( get_maybe_tuple_sharding(after_partial_replication), reduce, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); continue; } // Use the same sharding for all tuple elements, because they are part // of the same reduce instruction. HloSharding new_sharding = get_maybe_tuple_sharding(hlo_sharding_util::RemoveShapeDimensions( after_partial_replication, reduce->dimensions())); changed |= MaybeImproveInstructionSharding( std::move(new_sharding), reduce, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(reduce) == 1); } return changed; } auto get_maybe_tuple_sharding = [&](HloSharding sharding) { if (instruction->shape().IsArray()) { return sharding; } std::vector<HloSharding> tuple(instruction->shape().tuple_shapes_size(), std::move(sharding)); return HloSharding::Tuple(instruction->shape(), tuple); }; absl::c_any_of(instruction->dimensions(), [operand](int64_t dim) { return operand->sharding().tile_assignment().dim(dim) > 1; }))) { absl::StatusOr<bool> ProcessShardingInstruction( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads, bool replace_sharding_with_copy, absl::flat_hash_map<const HloInstruction*, std::vector<int64_t>>* unspecified_dims, std::vector<HloSharding>* saved_root_shardings, absl::flat_hash_map<int64_t, HloSharding>* saved_parameter_shardings, absl::flat_hash_map<HloInstruction*, int64_t>* instruction_to_shard_group_id, absl::flat_hash_map<int64_t, absl::flat_hash_set<HloInstruction*>>* shard_group_id_to_shard_as_group, absl::flat_hash_map<int64_t, absl::flat_hash_set<HloInstruction*>>* shard_group_id_to_shard_like_group, const std::vector<bool>* allow_spmd_sharding_propagation_to_parameters_vector) { bool changed = false; const bool use_shard_group = instruction_to_shard_group_id && shard_group_id_to_shard_as_group && shard_group_id_to_shard_like_group; // Process shard group instruction and returns if current instruction needs // to be removed. auto process_shard_group_instruction = [&](HloInstruction* instruction, bool replaced_with_copy) -> absl::StatusOr<bool> { // Run shard group processing IFF it's not CSE prevention. if (replace_sharding_with_copy) { if (use_shard_group && instruction->has_sharding() && instruction->sharding().IsShardGroup()) { if (instruction->IsCustomCall("Sharding")) { CHECK(instruction->operand(0)->opcode() != HloOpcode::kParameter || (allow_spmd_sharding_propagation_to_parameters_vector && allow_spmd_sharding_propagation_to_parameters_vector->size() == module->entry_computation()->num_parameters() && allow_spmd_sharding_propagation_to_parameters_vector->at( instruction->operand(0)->parameter_number()))); } if (instruction->IsCustomCall("Sharding") && !replaced_with_copy) { // Pass shard group to operand sharding custom-call if it's not // replaced with a copy, meaning that the shardings are to annotate // shard_group. HloSharding operand_sharding = instruction->operand(0)->has_sharding() ? instruction->operand(0)->sharding() : HloSharding::Unknown(); operand_sharding.SetShardGroup( instruction->sharding().GetShardGroup()); instruction->mutable_operand(0)->set_sharding( std::move(operand_sharding)); return true; } else { // Otherwise store the shard group relations. const int64_t shard_group_id = instruction->sharding().GetShardGroup().shard_group_id; (*instruction_to_shard_group_id)[instruction] = shard_group_id; if (instruction->sharding().IsShardAs()) { auto& shard_as_group = (*shard_group_id_to_shard_as_group)[shard_group_id]; if (!shard_as_group.empty()) { CHECK(ShapeUtil::SameDimensions( instruction->shape(), (*shard_as_group.begin())->shape())) << "Instruction: " << instruction->ToString() << " has different shape from the shapes of the other " "instructions within the same shard_as group: " << (*shard_as_group.begin())->shape().ToString(); } shard_as_group.insert(instruction); } else { auto& shard_like_group = (*shard_group_id_to_shard_like_group)[shard_group_id]; if (!shard_like_group.empty()) { CHECK(ShapeUtil::SameDimensions( instruction->shape(), (*shard_like_group.begin())->shape())) << "Instruction: " << instruction->ToString() << " has different shape from the shapes of the other " "instructions within the same shard_like group: " << (*shard_like_group.begin())->shape().ToString(); } shard_like_group.insert(instruction); } HloSharding sharding = instruction->sharding(); sharding.ClearShardGroup(); instruction->set_sharding(std::move(sharding)); } } } return false; }; for (HloComputation* computation : module->computations(execution_threads)) { auto instructions = computation->MakeInstructionPostOrder(); for (auto it = instructions.rbegin(); it != instructions.rend(); ++it) { HloInstruction* instruction = *it; if (instruction->IsCustomCall("Sharding")) { HloSharding original_sharding = instruction->sharding(); TF_RET_CHECK(instruction->has_sharding()) << "Sharding instruction must have a sharding attribute"; VLOG(3) << "ProcessShardingInstruction: " << instruction->ToString(); std::vector<int64_t> unspec_dims; TF_RETURN_IF_ERROR(sharding_op_util::ParseAttributes( Cast<HloCustomCallInstruction>(instruction)->opaque(), &unspec_dims)); bool replaced_with_copy = replace_sharding_with_copy && (!original_sharding.IsUnknown() || instruction->operand(0)->opcode() == HloOpcode::kParameter); // Replace the sharding instruction with a copy node so that it does not // need special handling. if (replaced_with_copy) { auto copy = computation->AddInstruction(HloInstruction::CreateUnary( instruction->shape(), HloOpcode::kCopy, instruction->mutable_operand(0))); TF_ASSIGN_OR_RETURN( std::ignore, computation->ReplaceInstruction( instruction, copy, /*preserve_sharding=*/false, /*relay_control_dependency=*/false, /*remove_unused_operands=*/false)); copy->set_sharding(std::move(original_sharding)); instruction = copy; changed = true; } TF_ASSIGN_OR_RETURN( bool shard_group_remove_instruction, process_shard_group_instruction(instruction, replaced_with_copy)); if (!unspec_dims.empty()) { absl::c_sort(unspec_dims); unspecified_dims->emplace(instruction, std::move(unspec_dims)); } else if (!instruction->operand(0)->has_sharding()) { instruction->mutable_operand(0)->set_sharding( instruction->sharding()); } if (shard_group_remove_instruction) { TF_ASSIGN_OR_RETURN(std::ignore, computation->ReplaceInstruction( instruction, instruction->mutable_operand(0), /*preserve_sharding=*/false, /*relay_control_dependency=*/false, /*remove_unused_operands=*/false)); } } else { TF_ASSIGN_OR_RETURN(std::ignore, process_shard_group_instruction( instruction, /*replaced_with_copy=*/false)); } } } // Save the original shardings of parameters/outputs. HloInstruction* root_instr = module->entry_computation()->root_instruction(); if (saved_root_shardings != nullptr && root_instr->shape().IsTuple() && root_instr->has_sharding()) { saved_root_shardings->reserve( root_instr->sharding().tuple_elements().size()); for (const HloSharding& sharding : root_instr->sharding().tuple_elements()) { saved_root_shardings->push_back(sharding); } } if (saved_parameter_shardings != nullptr) { auto params = module->entry_computation()->parameter_instructions(); for (int64_t i = 0; i < params.size(); ++i) { if (params[i]->has_sharding()) { saved_parameter_shardings->insert({i, params[i]->sharding()}); } } } return changed; } [&](HloInstruction* instruction, bool replaced_with_copy) -> absl::StatusOr<bool> { // Run shard group processing IFF it's not CSE prevention. if (replace_sharding_with_copy) { if (use_shard_group && instruction->has_sharding() && instruction->sharding().IsShardGroup()) { if (instruction->IsCustomCall("Sharding")) { CHECK(instruction->operand(0)->opcode() != HloOpcode::kParameter || (allow_spmd_sharding_propagation_to_parameters_vector && allow_spmd_sharding_propagation_to_parameters_vector->size() == module->entry_computation()->num_parameters() && allow_spmd_sharding_propagation_to_parameters_vector->at( instruction->operand(0)->parameter_number()))); } if (instruction->IsCustomCall("Sharding") && !replaced_with_copy) { // Pass shard group to operand sharding custom-call if it's not // replaced with a copy, meaning that the shardings are to annotate // shard_group. HloSharding operand_sharding = instruction->operand(0)->has_sharding() ? instruction->operand(0)->sharding() : HloSharding::Unknown(); operand_sharding.SetShardGroup( instruction->sharding().GetShardGroup()); instruction->mutable_operand(0)->set_sharding( std::move(operand_sharding)); return true; } else { // Otherwise store the shard group relations. const int64_t shard_group_id = instruction->sharding().GetShardGroup().shard_group_id; (*instruction_to_shard_group_id)[instruction] = shard_group_id; if (instruction->sharding().IsShardAs()) { auto& shard_as_group = (*shard_group_id_to_shard_as_group)[shard_group_id]; if (!shard_as_group.empty()) { CHECK(ShapeUtil::SameDimensions( instruction->shape(), (*shard_as_group.begin())->shape())) << "Instruction: " << instruction->ToString() << " has different shape from the shapes of the other " "instructions within the same shard_as group: " << (*shard_as_group.begin())->shape().ToString(); } shard_as_group.insert(instruction); } else { auto& shard_like_group = (*shard_group_id_to_shard_like_group)[shard_group_id]; if (!shard_like_group.empty()) { CHECK(ShapeUtil::SameDimensions( instruction->shape(), (*shard_like_group.begin())->shape())) << "Instruction: " << instruction->ToString() << " has different shape from the shapes of the other " "instructions within the same shard_like group: " << (*shard_like_group.begin())->shape().ToString(); } shard_like_group.insert(instruction); } HloSharding sharding = instruction->sharding(); sharding.ClearShardGroup(); instruction->set_sharding(std::move(sharding)); } } } return false; }; VLOG(3) << "ProcessShardingInstruction: " << instruction->ToString(); int64_t ComputeNonRootUsers(const HloInstruction* instr) { int64_t non_root_users = instr->users().size(); for (int i = 0; i < instr->users().size(); ++i) { if (instr->users()[i] == instr->parent()->root_instruction()) { --non_root_users; } } return non_root_users; } /*static*/ absl::Status ShardingPropagation::NormalizeDomain( const DomainMetadata::Domain& domain, const DomainMetadata* metadata) { if (metadata != nullptr) { TF_ASSIGN_OR_RETURN(const auto& sharding_metadata, ShardingMetadata::ToShardingMetadata(metadata)); const auto& sharding = sharding_metadata->sharding(); if (sharding != nullptr) { bool is_spatially_partitioned = !sharding->HasUniqueDevice(); if (sharding->IsTuple()) { is_spatially_partitioned = absl::c_any_of( sharding->tuple_elements(), [](const HloSharding& s) { return !s.HasUniqueDevice(); }); } if (is_spatially_partitioned) { for (HloInstruction* d : domain.exit_domains) { HloInstruction* operand = d->mutable_operand(0); // Set sharding only if it is different. We don't overwrite the // metadata if it has the same sharding besides metadata. if (!operand->has_sharding() || operand->sharding() != *sharding) { HloSharding operand_sharding = *sharding; if (operand->shape().IsTuple() && !sharding->IsTuple()) { // Expand sharding into tuple sharding per // CloneShardingForDomain() in // third_party/tensorflow/compiler/xla/hlo/ir/hlo_sharding_metadata.cc operand_sharding = HloSharding::SingleTuple(operand->shape(), *sharding); } operand->set_sharding(std::move(operand_sharding)); } } return absl::OkStatus(); } } } return ShardingMetadata::NormalizeShardingDomain(domain, metadata); } std::optional<HloSharding> ShardingPropagation::GetShardingFromUser( const HloInstruction& instruction, const HloInstruction& user, int64_t aggressiveness, bool is_spmd, const CallGraph& call_graph, const CustomCallShardingHelper* sharding_helper) { if (!CanPropagateThroughAtAggressiveLevel(user, aggressiveness)) { return std::nullopt; } if (!hlo_sharding_util::IsSpatiallyPartitioned(&user)) { return std::nullopt; } const bool may_combine_partial_sharding = is_spmd && aggressiveness > 0; switch (user.opcode()) { case HloOpcode::kBroadcast: { return InferBroadcastOperandSharding(user, is_spmd); } case HloOpcode::kConcatenate: { if (aggressiveness == 0) { return std::nullopt; } if (user.sharding().IsReplicated()) { return user.sharding(); } const int64_t cdim = user.concatenate_dimension(); auto& tile_assignment = user.sharding().tile_assignment(); if (tile_assignment.dim(cdim) == 1) { // If we are concatenating along a non-sharded dimension then the // operands should have the same sharding as the result. return user.sharding(); } if (is_spmd) { // SPMD doesn't support tiling with part of the devices. Return the same // sharding. return user.sharding(); } // If we are concatenating along a sharded dimension then we want the // operands to be distributed among the devices their data is used. int64_t start_offset = 0; for (HloInstruction* op : user.operands()) { if (op == &instruction) { break; } start_offset += op->shape().dimensions(cdim); } const int64_t tile_shape = CeilOfRatio( user.shape().dimensions(cdim), tile_assignment.dimensions()[cdim]); std::vector<int64_t> start_indices(tile_assignment.num_dimensions()); std::vector<int64_t> end_indices(tile_assignment.dimensions().begin(), tile_assignment.dimensions().end()); start_indices[cdim] = start_offset / tile_shape; end_indices[cdim] = CeilOfRatio( start_offset + instruction.shape().dimensions(cdim), tile_shape); auto new_tile_assignment = tile_assignment.array().Slice(start_indices, end_indices); if (new_tile_assignment.num_elements() == 1) { return HloSharding::AssignDevice(*new_tile_assignment.begin(), user.sharding().metadata()); } return HloSharding::Tile(std::move(new_tile_assignment), user.sharding().metadata()); } case HloOpcode::kConvolution: { auto dot_dims = dot_as_convolution_util::ParseConvolutionDimsInfo(&user); if (dot_dims.conv_spatial_dims.empty()) { int64_t op_idx = user.operand_index(&instruction); return hlo_sharding_util::InferDotOperandSharding( &user, op_idx, dot_dims, /*consider_other_operand=*/true, may_combine_partial_sharding); } return std::nullopt; } case HloOpcode::kDynamicSlice: case HloOpcode::kDynamicUpdateSlice: { if (aggressiveness == 0) { return std::nullopt; } if (user.sharding().IsReplicated()) { return user.sharding(); } if (user.opcode() == HloOpcode::kDynamicUpdateSlice && &instruction == user.operand(0)) { return user.sharding(); } const HloInstruction* operand = user.opcode() == HloOpcode::kDynamicSlice ? user.operand(0) : user.operand(1); if (&instruction != operand) { return std::nullopt; } if (is_spmd) { return user.sharding(); } const auto& tile_assignment = user.sharding().tile_assignment(); for (int64_t i = 0; i < user.shape().rank(); ++i) { if (tile_assignment.dim(i) > 1 && user.shape().dimensions(i) != operand->shape().dimensions(i)) { return std::nullopt; } } return user.sharding(); } case HloOpcode::kReduceWindow: { auto* reduce_window = Cast<HloReduceWindowInstruction>(&user); if (!absl::c_linear_search(reduce_window->inputs(), &instruction)) { return std::nullopt; } if (reduce_window->shape().IsTuple()) { auto sub_sharding = reduce_window->sharding().GetSubSharding( reduce_window->shape(), {reduce_window->operand_index(&instruction)}); return sub_sharding; } return reduce_window->sharding(); } case HloOpcode::kReshape: { return hlo_sharding_util::PropagateShardingThroughReshape( user.shape(), instruction.shape(), user.sharding()); } case HloOpcode::kPad: { if (&instruction != user.operand(0)) { return std::nullopt; } return user.sharding(); } case HloOpcode::kSlice: { return user.sharding(); } case HloOpcode::kTranspose: { // Calculate the dimension numbers for reversing the current transpose // and then use TransposeSharding to convert the output sharding to an // input sharding. std::vector<int64_t> reverse_dimensions(user.dimensions().size()); for (int64_t i = 0; i < user.dimensions().size(); ++i) { reverse_dimensions[user.dimensions(i)] = i; } return hlo_sharding_util::TransposeSharding(user.sharding(), reverse_dimensions); } case HloOpcode::kTuple: { auto sub_sharding = user.sharding().GetSubSharding( user.shape(), {user.operand_index(&instruction)}); // In case the instruction is used as the operands multiple times within // this tuple, we will return the most specific sharding and propagate up. for (int64_t i = 0; i < user.shape().tuple_shapes_size(); ++i) { if (user.operand(i) == &instruction) { // Only evaluate GetSubSharding if this operand is of interest, // as it is relatively expensive. HloSharding alternative_sub_sharding = user.sharding().GetSubSharding(user.shape(), {i}); if (hlo_sharding_util::IsShardingMoreSpecific( alternative_sub_sharding, sub_sharding)) { sub_sharding = alternative_sub_sharding; } } } return sub_sharding; } case HloOpcode::kGetTupleElement: { int64_t sharding_index = 0; for (int i = 0; i < instruction.shape().tuple_shapes_size(); ++i) { if (i == user.tuple_index()) { break; } if (instruction.shape().tuple_shapes(i).IsArray()) { sharding_index += 1; } else { sharding_index += ShapeUtil::GetLeafCount(instruction.shape().tuple_shapes(i)); } } if (user.shape().IsArray()) { // Use ReplicateAllDataDims instead of HloSharding::Replicate() to // preserve manual subgroups. HloSharding new_sharding = instruction.has_sharding() ? instruction.sharding() : HloSharding::SingleTuple( instruction.shape(), hlo_sharding_util::ReplicateAllDataDims(user.sharding())); new_sharding.tuple_elements()[sharding_index] = user.sharding(); return new_sharding; } else { if (user.sharding().tuple_elements().empty()) { return std::nullopt; } HloSharding new_sharding = instruction.has_sharding() ? instruction.sharding() : HloSharding::SingleTuple( instruction.shape(), hlo_sharding_util::ReplicateAllDataDims( user.sharding().tuple_elements()[0])); for (int64_t i = 0; i < user.sharding().tuple_elements().size(); ++i) { new_sharding.tuple_elements()[sharding_index + i] = user.sharding().tuple_elements()[i]; } return new_sharding; } } case HloOpcode::kDot: { int64_t op_idx = user.operand_index(&instruction); auto dnums = dot_as_convolution_util::ParseDotGeneralFromDot(&user); return hlo_sharding_util::InferDotOperandSharding( &user, op_idx, dnums, /*consider_other_operand=*/true, may_combine_partial_sharding); } case HloOpcode::kReduce: { if (instruction.shape().rank() == 0) { return std::nullopt; } auto user_sharding = user.shape().IsTuple() ? user.sharding().GetSubSharding( user.shape(), {user.operand_index(&instruction)}) : user.sharding(); if (!user_sharding.IsTileMaximal()) { std::vector<int64_t> target_tile_assignment_dimensions( instruction.shape().rank() + (user_sharding.ReplicateOnLastTileDim() ? 1 : 0) + user_sharding.subgroup_types().size()); const auto& dimensions = user.dimensions(); int64_t next_output_dim = 0; for (int64_t i = 0; i < target_tile_assignment_dimensions.size(); ++i) { if (absl::c_find(dimensions, i) == dimensions.end()) { target_tile_assignment_dimensions[i] = user_sharding.tile_assignment().dim(next_output_dim++); } else { target_tile_assignment_dimensions[i] = 1; } } auto tile_assignment = user_sharding.tile_assignment().Reshape( target_tile_assignment_dimensions); user_sharding = user_sharding.ReplicateOnLastTileDim() ? HloSharding::PartialTile(tile_assignment, user_sharding.metadata()) : HloSharding::Subgroup(tile_assignment, user_sharding.subgroup_types(), user_sharding.metadata()); } // Try to merge with sharding from other operands if they can improve // current sharding. const auto* reduce = Cast<const HloReduceInstruction>(&user); for (const HloInstruction* operand : reduce->inputs()) { if (operand != &instruction && operand->has_sharding()) { hlo_sharding_util::MergeShardingIfCompatible( operand->sharding(), user_sharding.NumTiles() + 1, &user_sharding); } } return user_sharding; } case HloOpcode::kSort: { HloSharding user_sharding = user.sharding(); if (user_sharding.IsTuple()) { return user_sharding.GetSubSharding(user.shape(), {user.operand_index(&instruction)}); } return user_sharding; } case HloOpcode::kReverse: { return hlo_sharding_util::ReverseSharding(user.sharding(), user.dimensions()); } case HloOpcode::kOutfeed: { if (&instruction != user.operand(0)) { return std::nullopt; } std::vector<Shape> operand_shapes(user.operand_count()); for (int i = 0; i < user.operand_count(); ++i) { operand_shapes[i] = user.operand(i)->shape(); } return user.sharding().GetSubSharding( ShapeUtil::MakeTupleShape(operand_shapes), {0}); } case HloOpcode::kGather: { if (&instruction == user.operand(1)) { return hlo_sharding_util:: GatherIndexShardingFromOutputIndexPassthroughDimensions( user.sharding(), &user); } if (is_spmd) { return hlo_sharding_util::GatherOperandShardingFromOutput( user.sharding(), user, call_graph); } return std::nullopt; } case HloOpcode::kScatter: { auto& scatter_user = *Cast<HloScatterInstruction>(&user); const int64_t operand_count = scatter_user.scatter_operand_count(); auto scatter_operands = scatter_user.scatter_operands(); auto scatter_indices = scatter_user.scatter_indices(); auto scatter_updates = scatter_user.scatter_updates(); // Infer sharding for scatter operand. const int64_t operand_index = absl::c_find(scatter_operands, &instruction) - scatter_operands.cbegin(); if (operand_index < operand_count) { return user.sharding().IsTuple() ? user.sharding().GetSubSharding( user.shape(), {operand_index}) : user.sharding(); } // Infer sharding for scatter indices. if (&instruction == scatter_indices) { std::vector<const HloInstruction*> partitioned_updates; for (const HloInstruction* update : scatter_updates) { if (hlo_sharding_util::IsSpatiallyPartitioned(update)) { partitioned_updates.push_back(update); } } if (partitioned_updates.empty()) { return std::nullopt; } std::vector<HloSharding> shardings; absl::c_transform( partitioned_updates, std::back_inserter(shardings), [&scatter_user](const HloInstruction* update) { return hlo_sharding_util:: ScatterIndexShardingFromUpdateIndexPassthroughDimensions( update->sharding(), &scatter_user); }); return hlo_sharding_util::FindCommonSharding(shardings); } // Infer sharding for scatter update. const int64_t update_index = absl::c_find(scatter_updates, &instruction) - scatter_updates.cbegin(); CHECK_LE(update_index, operand_count); auto from_indices = hlo_sharding_util::IsSpatiallyPartitioned(scatter_indices) ? hlo_sharding_util:: ScatterUpdateShardingFromIndexIndexPassthroughDimensions( scatter_indices->sharding(), &scatter_user) : HloSharding::Replicate(); if (is_spmd) { auto from_output = hlo_sharding_util::ScatterUpdateShardingFromOutput( user.sharding().IsTuple() ? user.sharding().GetSubSharding(user.shape(), {update_index}) : user.sharding(), scatter_user, call_graph); if (from_output.has_value()) { // Use sharding from output as primary sharding since it prioritize // parallel sharding first as this is how it is in spmd_partitioner. hlo_sharding_util::MergeShardingIfCompatible( from_indices, from_output->NumTiles() + 1, &*from_output); if (!from_output->IsTileMaximal()) { return from_output; } } } if (!from_indices.IsTileMaximal()) { return from_indices; } return std::nullopt; } case HloOpcode::kCustomCall: { bool compatible_shapes = ShapeUtil::CompatibleIgnoringElementType( instruction.shape(), user.shape()); if (!compatible_shapes) { // Incompatible shapes, we will not propagate sharding. return std::nullopt; } if (!sharding_helper) { // No available sharding helper and shapes are compatible, we will // propagate sharding. return user.sharding(); } if (sharding_helper->CanPropagateShardingToOperands(&user)) { return user.sharding(); } return std::nullopt; } default: { // If the user output shape is compatible with the current instruction // shape excluding element type and the current instruction is supported // by spatial partitioning, then the user sharding can be used for // propagation to the current instruction. if (ShapeUtil::CompatibleIgnoringElementType(instruction.shape(), user.shape())) { return user.sharding(); } return std::nullopt; } } } [&scatter_user](const HloInstruction* update) { return hlo_sharding_util:: ScatterIndexShardingFromUpdateIndexPassthroughDimensions( update->sharding(), &scatter_user); }); bool AggressiveConcatOperandShardingCanPassThrough( const HloInstruction* concat_operand) { return ( hlo_sharding_util::IsSpatiallyPartitioned(concat_operand) && (concat_operand->has_sharding() && concat_operand->sharding().NumTiles() > 1) && concat_operand->opcode() == HloOpcode::kReshape && (concat_operand->operand(0)->opcode() == HloOpcode::kParameter || concat_operand->operand(0)->opcode() == HloOpcode::kGetTupleElement)); } bool InferDynamicSliceOrDynamicUpdateSliceShardingFromOperands( HloInstruction* instruction, int64_t aggressiveness, bool may_combine_partial_sharding) { const HloInstruction* operand = instruction->opcode() == HloOpcode::kDynamicSlice ? instruction->operand(0) : instruction->operand(1); auto slice_dim_is_sharded = [&]() { if (!hlo_sharding_util::IsSpatiallyPartitioned(operand) || operand->sharding().IsManual() || operand->sharding().NumTiles() == 1) { return false; } for (int64_t i = 0; i < instruction->shape().rank(); ++i) { const auto& tile_assignment = operand->sharding().tile_assignment(); if (tile_assignment.dim(i) > 1 && instruction->shape().dimensions(i) != operand->shape().dimensions(i)) { return true; } } return false; }; // Do not pass through sharding annotation at the first iteration // if slice dim is sharded. if (aggressiveness == 0 && slice_dim_is_sharded()) { return false; } auto propagate_slicing = [&]() { if (!hlo_sharding_util::IsSpatiallyPartitioned(operand)) { return false; } if (slice_dim_is_sharded()) { return false; } return MaybeImproveInstructionSharding( operand->sharding(), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); }; auto propagate_base = [&]() { if (instruction->opcode() != HloOpcode::kDynamicUpdateSlice) { return false; } if (!hlo_sharding_util::IsSpatiallyPartitioned(instruction->operand(0))) { return false; } return MaybeImproveInstructionSharding(instruction->operand(0)->sharding(), instruction, may_combine_partial_sharding); }; bool changed = propagate_slicing(); changed |= propagate_base(); return changed; } auto slice_dim_is_sharded = [&]() { if (!hlo_sharding_util::IsSpatiallyPartitioned(operand) || operand->sharding().IsManual() || operand->sharding().NumTiles() == 1) { return false; } for (int64_t i = 0; i < instruction->shape().rank(); ++i) { const auto& tile_assignment = operand->sharding().tile_assignment(); if (tile_assignment.dim(i) > 1 && instruction->shape().dimensions(i) != operand->shape().dimensions(i)) { return true; } } return false; }; auto propagate_slicing = [&]() { if (!hlo_sharding_util::IsSpatiallyPartitioned(operand)) { return false; } if (slice_dim_is_sharded()) { return false; } return MaybeImproveInstructionSharding( operand->sharding(), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); }; auto propagate_base = [&]() { if (instruction->opcode() != HloOpcode::kDynamicUpdateSlice) { return false; } if (!hlo_sharding_util::IsSpatiallyPartitioned(instruction->operand(0))) { return false; } return MaybeImproveInstructionSharding(instruction->operand(0)->sharding(), instruction, may_combine_partial_sharding); }; bool ShardingPropagation::InferShardingFromShardGroup( HloInstruction* instruction, const ComputationMap& computation_map, int64_t aggressiveness, const absl::flat_hash_set<HloInstruction*>& shard_group) { if (!CanPropagateThroughAtAggressiveLevel(*instruction, aggressiveness)) { return false; } // Do not change manual sharding. if (instruction->has_sharding() && instruction->sharding().IsManual()) { return false; } // Do not propagate sharding to ShardBarrierTo custom-call. if (instruction->IsCustomCall(spmd::kShardBarrierTo)) { return false; } // Propagate manual sharding. if (!instruction->has_sharding() || instruction->sharding().IsTileMaximal()) { for (const HloInstruction* member : shard_group) { if (!member->has_sharding() || !member->sharding().IsManual() || member == instruction) { continue; } instruction->set_sharding(member->sharding()); return true; } } const bool may_combine_partial_sharding = is_spmd_ && aggressiveness > 0; bool changed = false; for (const HloInstruction* member : shard_group) { // Do not propagate sharding from ShardBarrierFrom custom-call. if (member == instruction || member->IsCustomCall(spmd::kShardBarrierFrom)) { continue; } changed |= MaybeImproveInstructionSharding(member->sharding(), instruction, may_combine_partial_sharding); } return changed; } bool ShardingPropagation::InferShardingFromOperands( HloInstruction* instruction, const ComputationMap& computation_map, int64_t aggressiveness, const CallGraph& call_graph, const absl::flat_hash_set<absl::string_view>& execution_threads) { if (!CanPropagateThroughAtAggressiveLevel(*instruction, aggressiveness)) { return false; } // Do not change manual sharding. if (instruction->has_sharding() && instruction->sharding().IsManual()) { return false; } // Propagate manual sharding. Avoid tuple shaped HLOs that group independent // together. Reduce, ReduceWindow, and Sort can be tuples but the elements // are correlated, so we propagate manual sharding through them. // For custom-calls with manual operand, the default propagation logic will // just assign manual to the whole custom-call. const bool custom_call_condition = instruction->opcode() == HloOpcode::kCustomCall && instruction->shape().IsTuple(); // For asynchronous instructions with manual operand, we assign manual to the // whole instructions if the async_execution_thread is not in the // execution_threads. const bool async_instr_condition = instruction->IsAsynchronous() && !HloInstruction::IsThreadIncluded(instruction->async_execution_thread(), execution_threads); if ((!instruction->has_sharding() || instruction->sharding().IsTileMaximal()) && (instruction->shape().IsArray() || instruction->opcode() == HloOpcode::kReduce || instruction->opcode() == HloOpcode::kSort || instruction->opcode() == HloOpcode::kReduceWindow || custom_call_condition || async_instr_condition)) { for (const HloInstruction* op : instruction->operands()) { if (!op->has_sharding() || !op->sharding().IsManual()) continue; // Do not pass through manual sharding to SPMDShardToFullShape. if (instruction->IsCustomCall("SPMDShardToFullShape")) { return false; } // Do not pass through manual sharding to concat or dynamic slice when // aggressiveneess is 0. if (aggressiveness == 0 && (instruction->opcode() == HloOpcode::kConcatenate || instruction->opcode() == HloOpcode::kDynamicSlice)) { return false; } instruction->set_sharding( HloSharding::Manual(op->sharding().metadata()) .NormalizeTupleSharding(instruction->shape())); return true; } } const bool may_combine_partial_sharding = is_spmd_ && aggressiveness > 0; if (!SupportSpatialPartitioning( instruction, computation_map, is_spmd_, allow_spmd_sharding_propagation_to_output_, /*allow_spmd_sharding_propagation_to_parameters=*/false, sharding_helper_.get())) { // If an array shaped HLO doesn't support spatial partitioning but at least // one of its operand is replicated then we make the HLO replicated as well. if (instruction->shape().IsTuple() || instruction->operand_count() == 0 || instruction == instruction->parent()->root_instruction() || instruction->HasSideEffect()) { return false; } for (const HloInstruction* op : instruction->operands()) { if (op->has_sharding() && op->sharding().IsTileMaximal() && !op->sharding().HasUniqueDevice()) { return MaybeImproveInstructionSharding(op->sharding(), instruction, may_combine_partial_sharding); } } return false; } auto get_maybe_tuple_sharding = [&](HloSharding sharding) { if (instruction->shape().IsArray()) { return sharding; } std::vector<HloSharding> tuple(instruction->shape().tuple_shapes_size(), std::move(sharding)); return HloSharding::Tuple(instruction->shape(), tuple); }; switch (instruction->opcode()) { case HloOpcode::kGetTupleElement: { const HloInstruction* operand = instruction->operand(0); if (!hlo_sharding_util::IsSpatiallyPartitioned(operand)) { return false; } HloSharding new_sharding = operand->sharding().GetSubSharding( operand->shape(), {instruction->tuple_index()}); if (new_sharding.IsManual()) { instruction->set_sharding(std::move(new_sharding)); return true; } return MaybeImproveInstructionSharding( std::move(new_sharding), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); } case HloOpcode::kTuple: { if (absl::c_none_of( instruction->operands(), [](const HloInstruction* hlo) { return hlo_sharding_util::IsSpatiallyPartitioned(hlo); })) { // None of the operands have a spatially partitioned sharding. return false; } const Shape& shape = instruction->shape(); // Go through each operand and if the operand has a sharding that is // better than the current sharding for that tuple element then update // it. If the current sharding does not exist, assume its replicated. std::vector<HloSharding> sub_shardings; if (instruction->has_sharding()) { sub_shardings = instruction->sharding().tuple_elements(); } else { // If instruction does not have a sharding, assume its replicated to // allow refinement. sub_shardings.assign(HloSharding::RequiredLeaves(shape), HloSharding::Replicate()); } // This is required to allow manual sharding on operands to be propagated // to the tuple. hlo_sharding_util::IsShardingMoreSpecific() returns false // if any of the shardings involved is manual, so using it directly will // prevent manual sharding on an operand to be propagated to the tuple // when it has no existing sharding. auto is_more_specific = [instruction](const HloSharding& operand_sharding, const HloSharding& existing) { // If the instruction originally had no sharding, always prefer operand // sharding. return !instruction->has_sharding() || hlo_sharding_util::IsShardingMoreSpecific(operand_sharding, existing); }; int64_t sub_sharding_index = 0; for (int64_t i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const HloInstruction* operand = instruction->operand(i); if (operand->has_sharding()) { if (operand->shape().IsTuple()) { for (int64_t j = 0, e = ShapeUtil::GetLeafCount(operand->shape()); j < e; ++j) { if (is_more_specific(operand->sharding().tuple_elements()[j], sub_shardings[sub_sharding_index + j])) { sub_shardings[sub_sharding_index + j] = operand->sharding().tuple_elements()[j]; } } } else { std::optional<HloSharding> op_sharding = hlo_sharding_util::GetOutputSharding(operand); CHECK(op_sharding.has_value()) << "Expected sharding for " << operand->ToString(); if (is_more_specific(op_sharding.value(), sub_shardings[sub_sharding_index])) { sub_shardings[sub_sharding_index] = op_sharding.value(); } } } sub_sharding_index += ShapeUtil::GetLeafCount(operand->shape()); } HloSharding new_sharding = HloSharding::Tuple(shape, sub_shardings); if (!instruction->has_sharding() || new_sharding != instruction->sharding()) { instruction->set_sharding(std::move(new_sharding)); return true; } return false; } case HloOpcode::kReduce: { // Reduce could have a tuple shape, where the first half of operands are // the arrays to reduce, and the second half of operands are the init // values. return InferReduceShardingFromOperand( instruction, may_combine_partial_sharding, is_spmd_); } case HloOpcode::kBroadcast: { // Make forward propagation through broadcast low priority to avoid // resharding after broadcast. if (aggressiveness < 3) { return false; } const HloInstruction* op = instruction->operand(0); if (!hlo_sharding_util::IsSpatiallyPartitioned(op) || op->sharding().IsReplicated()) { return false; } // The output will be tiled along the broadcasted dimension the same way // as the input for the broadcast while the other dimensions are kept // non-tiled. std::vector<int64_t> target_tile_assignment_dimensions; const auto& dimensions = instruction->dimensions(); for (int64_t i = 0; i < instruction->shape().rank(); ++i) { auto it = absl::c_find(dimensions, i); if (it == dimensions.end()) { target_tile_assignment_dimensions.push_back(1); } else { const int64_t source_dim = std::distance(dimensions.begin(), it); target_tile_assignment_dimensions.push_back( op->sharding().tile_assignment().dim(source_dim)); } } for (int64_t i = op->sharding().TiledDataRank(); i < op->sharding().tile_assignment().num_dimensions(); ++i) { target_tile_assignment_dimensions.push_back( op->sharding().tile_assignment().dim(i)); } auto new_tile_assignment = op->sharding().tile_assignment().Reshape( target_tile_assignment_dimensions); HloSharding new_sharding = op->sharding().ReplicateOnLastTileDim() ? HloSharding::PartialTile(new_tile_assignment, op->sharding().metadata()) : HloSharding::Subgroup(new_tile_assignment, op->sharding().subgroup_types(), op->sharding().metadata()); return MaybeImproveInstructionSharding( std::move(new_sharding), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ComputeNonRootUsers(instruction) == 1); } case HloOpcode::kConcatenate: { const HloInstruction* operand = PickRepresentativeOperand(instruction); if (!operand || !hlo_sharding_util::IsSpatiallyPartitioned(operand)) { return false; } if (aggressiveness == 0) { for (const HloInstruction* concat_operand : instruction->operands()) { if (!AggressiveConcatOperandShardingCanPassThrough(concat_operand)) { return false; } const auto& tile_assignment = concat_operand->sharding().tile_assignment(); for (int64_t i = 0; i < instruction->shape().rank(); ++i) { if (absl::c_linear_search(instruction->dimensions(), i) && tile_assignment.dim(i) > 1) { return false; } } } } return MaybeImproveInstructionSharding( operand->sharding(), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ComputeNonRootUsers(instruction) == 1); } case HloOpcode::kConvolution: return InferConvolutionShardingFromOperands( instruction, call_graph, aggressiveness, may_combine_partial_sharding, is_spmd_); case HloOpcode::kTranspose: { const HloInstruction* input = instruction->operand(0); if (!hlo_sharding_util::IsSpatiallyPartitioned(input)) { return false; } HloSharding sharding = hlo_sharding_util::TransposeSharding( input->sharding(), instruction->dimensions()); return MaybeImproveInstructionSharding( std::move(sharding), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ComputeNonRootUsers(instruction) == 1); } case HloOpcode::kReduceWindow: { auto* reduce_window = Cast<HloReduceWindowInstruction>(instruction); auto has_dilation = [](const WindowDimension& dimensions) { return dimensions.base_dilation() > 1 || dimensions.window_dilation() > 1; }; if (absl::c_any_of(instruction->window().dimensions(), has_dilation)) { VLOG(2) << "Not applying sharding to reduce window because dilatation " "isn't supported yet: " << reduce_window->ToString(); return false; } bool changed = false; for (HloInstruction* operand : reduce_window->inputs()) { if (!hlo_sharding_util::IsSpatiallyPartitioned(operand)) { continue; } changed |= MaybeImproveInstructionSharding( get_maybe_tuple_sharding(operand->sharding()), reduce_window, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); } return changed; } case HloOpcode::kSelectAndScatter: { // Shard according to first operand, as output keeps the same shape. const HloInstruction* lhs = instruction->operand(0); if (!hlo_sharding_util::IsSpatiallyPartitioned(lhs)) { return false; } auto has_base_dilation = [](const WindowDimension& dimensions) { return dimensions.base_dilation() > 1; }; if (absl::c_any_of(instruction->window().dimensions(), has_base_dilation)) { VLOG(2) << "Not applying sharding to select-and-scatter because " "base dilation isn't supported yet: " << instruction->ToString(); return false; } return MaybeImproveInstructionSharding( lhs->sharding(), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ComputeNonRootUsers(instruction) == 1); } case HloOpcode::kReshape: { if (!hlo_sharding_util::IsSpatiallyPartitioned(instruction->operand(0))) { return false; } HloSharding new_sharding = hlo_sharding_util::PropagateShardingThroughReshape( instruction->operand(0)->shape(), instruction->shape(), instruction->operand(0)->sharding()); return MaybeImproveInstructionSharding( std::move(new_sharding), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); return false; } case HloOpcode::kReverse: { const HloInstruction* operand = instruction->operand(0); if (!hlo_sharding_util::IsSpatiallyPartitioned(operand)) { return false; } return MaybeImproveInstructionSharding( hlo_sharding_util::ReverseSharding(operand->sharding(), instruction->dimensions()), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ComputeNonRootUsers(instruction) == 1); } case HloOpcode::kDot: { const auto& dnums = dot_as_convolution_util::ParseDotGeneralFromDot(instruction); return InferDotShardingFromOperands(instruction, call_graph, dnums, may_combine_partial_sharding, is_spmd_); } case HloOpcode::kParameter: { auto parent_it = computation_map.find(instruction->parent()); if (parent_it == computation_map.end()) { return false; } const HloInstruction* parent = parent_it->second; switch (parent->opcode()) { case HloOpcode::kConditional: { for (int64_t i = 1; i < parent->operand_count(); ++i) { if (parent->called_computations()[i - 1] == instruction->parent()) { if (parent->operand(i)->has_sharding()) { return MaybeImproveInstructionSharding( parent->operand(i)->sharding(), instruction, may_combine_partial_sharding); } return false; } } return false; } case HloOpcode::kCall: { int64_t i = instruction->parameter_number(); if (parent->operand(i)->has_sharding()) { return MaybeImproveInstructionSharding( parent->operand(i)->sharding(), instruction, may_combine_partial_sharding); } return false; } default: return false; } } case HloOpcode::kSort: { const HloInstruction* operand = PickRepresentativeOperand(instruction); if (!operand || !hlo_sharding_util::IsSpatiallyPartitioned(operand)) { return false; } HloSortInstruction* sort = DynCast<HloSortInstruction>(instruction); CHECK(sort); const int64_t sort_dim = sort->sort_dimension(); if (!operand->sharding().IsTileMaximal() && operand->sharding().tile_assignment().dim(sort_dim) != 1) { // In case of a sort operand sharded along the sort dimension, the // sharding is propagated only if there exists a free (unsharded) // dimension that we can later move the sharding into. if (!hlo_sharding_util::IsSortOperandShardingMovable(operand, sort_dim)) return false; } if (instruction->shape().IsTuple()) { return MaybeImproveInstructionSharding( HloSharding::SingleTuple(instruction->shape(), operand->sharding()), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); } else { return MaybeImproveInstructionSharding( operand->sharding(), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); } } case HloOpcode::kDynamicSlice: case HloOpcode::kDynamicUpdateSlice: { return InferDynamicSliceOrDynamicUpdateSliceShardingFromOperands( instruction, aggressiveness, may_combine_partial_sharding); } case HloOpcode::kGather: { bool changed = false; if (hlo_sharding_util::IsSpatiallyPartitioned(instruction->operand(1))) { HloSharding new_sharding = hlo_sharding_util:: GatherOutputShardingFromIndexIndexPassthroughDimensions( instruction->operand(1)->sharding(), instruction); changed |= MaybeImproveInstructionSharding( std::move(new_sharding), instruction, may_combine_partial_sharding); } if (is_spmd_) { auto gather_parallel_dims = hlo_sharding_util::GetGatherParallelBatchDims(*instruction, call_graph); if (gather_parallel_dims) { changed |= InferGatherParallelShardingFromOperands( instruction, *gather_parallel_dims, may_combine_partial_sharding); } if (hlo_sharding_util::IsSpatiallyPartitioned( instruction->operand(0))) { absl::Span<const int64_t> operand_parallel_dims; if (gather_parallel_dims) { operand_parallel_dims = absl::MakeConstSpan( gather_parallel_dims->operand_parallel_dims); } HloSharding filtered_operand_sharding = hlo_sharding_util::PartiallyReplicateTiledShardingOnDims( instruction->operand(0)->sharding(), operand_parallel_dims); auto maybe_from_data = hlo_sharding_util:: GatherOutputShardingFromOperandOperandPassthroughDimensions( filtered_operand_sharding, *instruction); if (maybe_from_data) { changed |= MaybeImproveInstructionSharding( std::move(*maybe_from_data), instruction, may_combine_partial_sharding); } } } return changed; } case HloOpcode::kScatter: { auto& scatter = *Cast<HloScatterInstruction>(instruction); const int64_t operand_count = scatter.scatter_operand_count(); auto scatter_operands = scatter.scatter_operands(); auto scatter_indices = scatter.scatter_indices(); auto scatter_updates = scatter.scatter_updates(); bool changed = false; if (is_spmd_) { for (int64_t i = 0; i != operand_count; ++i) { if (hlo_sharding_util::IsSpatiallyPartitioned(scatter_operands[i])) { changed |= MaybeImproveInstructionSubSharding( scatter_operands[i]->sharding(), instruction, {i}, may_combine_partial_sharding); } } if (!hlo_sharding_util::IsSpatiallyPartitioned(scatter_indices) && absl::c_none_of(scatter_updates, [](const HloInstruction* update) { return hlo_sharding_util::IsSpatiallyPartitioned(update); })) { return changed; } auto scatter_parallel_dims = hlo_sharding_util::GetScatterParallelBatchDims(*instruction, call_graph); if (scatter_parallel_dims) { changed |= InferScatterParallelShardingFromOperands( instruction, *scatter_parallel_dims, may_combine_partial_sharding); } for (int64_t i = 0; i != operand_count; ++i) { if (hlo_sharding_util::IsSpatiallyPartitioned(scatter_updates[i])) { auto maybe_from_update = hlo_sharding_util::ScatterOutputShardingFromUpdate( scatter_updates[i]->sharding(), scatter); if (maybe_from_update) { changed |= MaybeImproveInstructionSubSharding( std::move(*maybe_from_update), instruction, {i}, may_combine_partial_sharding); } } } } else { for (int64_t i = 0; i != operand_count; ++i) { changed |= MaybeImproveInstructionSubSharding( HloSharding::Replicate(), instruction, {i}, may_combine_partial_sharding); } } return changed; } case HloOpcode::kWhile: { if (!instruction->operand(0)->has_sharding()) { return false; } auto sharding = instruction->operand(0)->sharding(); if (instruction->has_sharding()) { hlo_sharding_util::MergeSharding(instruction->sharding(), &sharding, may_combine_partial_sharding); } return MaybeImproveInstructionSharding(std::move(sharding), instruction, may_combine_partial_sharding); } case HloOpcode::kCustomCall: { HloSharding inferred_operand_sharding = HloSharding::Replicate(); if (auto* partitioner = GetCustomCallPartitioner(instruction->custom_call_target()); partitioner && partitioner->IsCustomCallShardable(instruction)) { if (auto sharding = partitioner->InferShardingFromOperands(instruction)) { inferred_operand_sharding = *sharding; } else { return false; } } else if (sharding_helper_->IsCustomCallShardable(instruction)) { if (auto sharding = sharding_helper_->InferShardingFromOperands(instruction)) { inferred_operand_sharding = *sharding; } else { return false; } } else { const HloInstruction* operand = PickRepresentativeOperand(instruction); if (!operand || !hlo_sharding_util::IsSpatiallyPartitioned(operand)) { return false; } inferred_operand_sharding = operand->sharding(); } return MaybeImproveInstructionSharding( inferred_operand_sharding, instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ComputeNonRootUsers(instruction) == 1); } default: { if (instruction->IsElementwise() && may_combine_partial_sharding) { bool changed = false; for (auto operand : instruction->operands()) { if (hlo_sharding_util::IsSpatiallyPartitioned(operand)) { if (instruction->opcode() == HloOpcode::kRng) { // Rng is considered elementwise but has operands with different // shapes. changed |= MaybeImproveInstructionSharding( hlo_sharding_util::ReplicateAllDataDims( operand->sharding(), instruction->shape().rank()), instruction, may_combine_partial_sharding, ComputeNonRootUsers(instruction) == 1); continue; } changed |= MaybeImproveInstructionSharding( operand->sharding(), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ instruction->operands().size() == 1 && ComputeNonRootUsers(instruction) == 1); } } return changed; } const HloInstruction* operand = PickRepresentativeOperand(instruction); if (!operand || !hlo_sharding_util::IsSpatiallyPartitioned(operand)) { return false; } return MaybeImproveInstructionSharding( operand->sharding(), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ComputeNonRootUsers(instruction) == 1); } } return false; } // NOLINT(readability/fn_size) auto get_maybe_tuple_sharding = [&](HloSharding sharding) { if (instruction->shape().IsArray()) { return sharding; } std::vector<HloSharding> tuple(instruction->shape().tuple_shapes_size(), std::move(sharding)); return HloSharding::Tuple(instruction->shape(), tuple); }; auto is_more_specific = [instruction](const HloSharding& operand_sharding, const HloSharding& existing) { // If the instruction originally had no sharding, always prefer operand // sharding. return !instruction->has_sharding() || hlo_sharding_util::IsShardingMoreSpecific(operand_sharding, existing); }; VLOG(2) << "Not applying sharding to reduce window because dilatation " VLOG(2) << "Not applying sharding to select-and-scatter because " bool ShardingPropagation::InferShardingFromUsers( HloInstruction* instruction, const ShardingPropagation::ComputationMap& computation_map, int64_t aggressiveness, bool is_spmd, const CustomCallShardingHelper* sharding_helper, const CallGraph& call_graph) { if (aggressiveness < 2 && instruction->opcode() == HloOpcode::kBroadcast) { return false; } // Do not change manual sharding. if (instruction->has_sharding() && instruction->sharding().IsManual()) { return false; } // Propagate manual sharding. if (!instruction->has_sharding() || instruction->sharding().IsTileMaximal()) { for (const HloInstruction* user : instruction->users()) { if (!user->has_sharding() || user->IsCustomCall("SPMDFullToShardShape")) continue; if (instruction->shape().IsArray() && user->sharding().IsManual()) { instruction->set_sharding( HloSharding::Manual(user->sharding().metadata())); return true; } else { std::optional<HloSharding> user_sharding = ShardingPropagation::GetShardingFromUser( *instruction, *user, aggressiveness, is_spmd, call_graph, sharding_helper); if (user_sharding && user_sharding->IsManual()) { instruction->set_sharding(std::move(*user_sharding)); return true; } } } } if (!SupportSpatialPartitioning( instruction, computation_map, is_spmd, /*allow_spmd_sharding_propagation_to_output=*/false, allow_spmd_sharding_propagation_to_parameters_, sharding_helper)) { return false; } bool improved_sharding = false; const bool may_combine_partial_sharding = is_spmd && aggressiveness > 0; for (const HloInstruction* user : instruction->users()) { std::optional<HloSharding> user_sharding = ShardingPropagation::GetShardingFromUser(*instruction, *user, aggressiveness, is_spmd, call_graph, sharding_helper); if (user_sharding && instruction->opcode() == HloOpcode::kCustomCall) { if (auto* partitioner = GetCustomCallPartitioner(instruction->custom_call_target())) { if (partitioner->IsCustomCallShardable(instruction)) { user_sharding = partitioner->PropagateUserSharding(instruction, user, *user_sharding); } } else if (sharding_helper->IsCustomCallShardable(instruction)) { user_sharding = sharding_helper->PropagateUserSharding( instruction, user, *user_sharding); } } if (user_sharding) { improved_sharding |= MaybeImproveInstructionSharding( std::move(*user_sharding), instruction, may_combine_partial_sharding); } } return improved_sharding; } absl::StatusOr<bool> ShardingPropagation::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { // Register custom-call partitioner for SharBarrierFrom and ShardBarrierTo. ABSL_CONST_INIT static absl::once_flag did_registration; absl::call_once(did_registration, [] { RegisterCustomCallPartitioner( spmd::kShardBarrierFrom, std::make_unique<spmd::ShardBarrierFromPartitioner>()); RegisterCustomCallPartitioner( spmd::kShardBarrierTo, std::make_unique<spmd::ShardBarrierToPartitioner>()); }); std::optional<absl::flat_hash_map<const HloInstruction*, HloSharding>> original_sharding; bool any_changed = false; // Preprocessing for CSE prevention propagation: record the original shardings // so that we can revert to them at the end, and only keep those on CSE // prevention instructions. if (cse_prevention_only_) { original_sharding.emplace(); for (auto computation : module->computations(execution_threads)) { for (auto instruction : computation->instructions()) { if (instruction->has_sharding()) { original_sharding->emplace(instruction, instruction->sharding()); } } } } else { // The current pass is not for CSE prevention, but we remove the shardings // added by previous passes for CSE prevention. for (auto computation : module->computations(execution_threads)) { for (auto instruction : computation->instructions()) { if (instruction->has_sharding() && IsCSEPreventionSharding(instruction->sharding())) { instruction->clear_sharding(); any_changed = true; } } } } any_changed |= propagate_metadata_ ? AssignShardingMetadata(module, execution_threads) : RemoveShardingMetadata(module, execution_threads); absl::flat_hash_map<const HloInstruction*, std::vector<int64_t>> unspecified_dims; std::vector<HloSharding> saved_root_shardings; absl::flat_hash_map<int64_t, HloSharding> saved_parameter_shardings; absl::flat_hash_map<HloInstruction*, int64_t> instruction_to_shard_group_id; absl::flat_hash_map<int64_t, absl::flat_hash_set<HloInstruction*>> shard_group_id_to_shard_as_group; absl::flat_hash_map<int64_t, absl::flat_hash_set<HloInstruction*>> shard_group_id_to_shard_like_group; TF_ASSIGN_OR_RETURN( bool changed, ProcessShardingInstruction( module, execution_threads, !cse_prevention_only_, &unspecified_dims, allow_spmd_sharding_propagation_to_output_ ? &saved_root_shardings : nullptr, allow_spmd_sharding_propagation_to_parameters_ ? &saved_parameter_shardings : nullptr, &instruction_to_shard_group_id, &shard_group_id_to_shard_as_group, &shard_group_id_to_shard_like_group, &allow_spmd_sharding_propagation_to_parameters_vector_)); any_changed |= changed; for (const auto& [shard_group_id, shard_as_group] : shard_group_id_to_shard_as_group) { VLOG(5) << "Shard-As group " << shard_group_id << " contains:"; for (auto instruction : shard_as_group) { VLOG(5) << " " << instruction->ToString(); } } for (const auto& [shard_group_id, shard_like_group] : shard_group_id_to_shard_like_group) { VLOG(5) << "Shard-Like group " << shard_group_id << " contains:"; for (auto instruction : shard_like_group) { VLOG(5) << " " << instruction->ToString(); } } // Check sizes of the given allow_spmd_sharding_propagation vectors if (allow_spmd_sharding_propagation_to_output_) { CHECK(!module->entry_computation()->root_instruction()->has_sharding() || allow_spmd_sharding_propagation_to_output_vector_.size() == 1 || module->entry_computation() ->root_instruction() ->sharding() .tuple_elements() .size() == allow_spmd_sharding_propagation_to_output_vector_.size()) << "allow-spmd-sharding-propagation-to-output-vector's size can be " "either 1 or the number of elements in the root tuple of entry " "computation."; } if (allow_spmd_sharding_propagation_to_parameters_) { auto is_same_sized_tuple = [](HloModule* module, int64_t size) { if (module->entry_computation()->num_parameters() != 1) { return false; } HloInstruction* param = module->entry_computation()->parameter_instruction(0); return param->shape().IsTuple() && size == param->shape().tuple_shapes_size(); }; auto size = allow_spmd_sharding_propagation_to_parameters_vector_.size(); CHECK(size == 1 || size == module->entry_computation()->num_parameters() || is_same_sized_tuple(module, size)) << "allow-spmd-sharding-propagation-to-parameters-vector's size can be " "either 1 or the number of parameters in the entry computation."; } // Association of partitionable embedded computations with their parent // instruction. ComputationMap computation_map; // Instructions that are related through a computation and need to share the // same sharding. auto get_related_instructions = [this](HloInstruction* inst) { if (inst->opcode() == HloOpcode::kWhile) { return std::vector<HloInstruction*>{ inst, inst->while_body()->root_instruction(), inst->while_body()->parameter_instruction(0), inst->while_condition()->parameter_instruction(0)}; } else if (inst->opcode() == HloOpcode::kConditional) { const auto& called_computations = inst->called_computations(); std::vector<HloInstruction*> comps; comps.reserve(called_computations.size() + 1); comps.push_back(inst); for (HloComputation* c : called_computations) { comps.push_back(c->root_instruction()); } return comps; } else if (inst->opcode() == HloOpcode::kCustomCall) { if (sharding_helper_ && sharding_helper_->IsCustomCallShardable(inst)) { return sharding_helper_->GetRelatedInstructions(inst); } else { return std::vector<HloInstruction*>{}; } } else if (inst->opcode() == HloOpcode::kCall) { HloComputation* callee = inst->called_computations().front(); return std::vector<HloInstruction*>{inst, callee->root_instruction()}; } else { CHECK(false); } }; // If instruction is a while, or the root or a parameter of a while body, // then propagate its sharding to the while instruction, to its body root, // and to its condition parameter. std::function<void(HloInstruction*, absl::flat_hash_set<HloInstruction*>*)> maybe_computation_propagation = [&](HloInstruction* instruction, absl::flat_hash_set<HloInstruction*>* changed) { auto propagate_to_instruction = [&](HloInstruction* search_inst) { auto related_instructions = get_related_instructions(search_inst); if (absl::c_count(related_instructions, instruction)) { for (HloInstruction* inst : related_instructions) { if (!inst->has_sharding() || inst->sharding() != instruction->sharding()) { VLOG(2) << "Add computation sharding: " << inst->name() << " " << instruction->sharding().ToString(); inst->copy_sharding(instruction); changed->insert(inst); maybe_computation_propagation(inst, changed); } } } }; if (instruction->opcode() == HloOpcode::kConditional || instruction->opcode() == HloOpcode::kWhile || instruction->opcode() == HloOpcode::kCustomCall || instruction->opcode() == HloOpcode::kCall) { propagate_to_instruction(instruction); } if (instruction->opcode() == HloOpcode::kParameter || instruction->parent()->root_instruction() == instruction) { auto it = computation_map.find(instruction->parent()); if (it != computation_map.end()) { propagate_to_instruction(it->second); } } }; for (auto computation : module->computations(execution_threads)) { for (auto instruction : computation->instructions()) { if (instruction->opcode() == HloOpcode::kWhile) { TF_RETURN_IF_ERROR( CheckAndUpdateDeviceAssignmentsInWhileBody(instruction)); } } } // Populate computation_map in order to associate while bodies to their // while instructions. for (auto computation : module->computations(execution_threads)) { for (auto instruction : computation->instructions()) { if (instruction->opcode() == HloOpcode::kWhile || instruction->opcode() == HloOpcode::kConditional || instruction->opcode() == HloOpcode::kCall) { // Check if any of the related instructions has sharding, in which case // propagate it to the other instructions, so they all share the same // sharding, in case the user didn't shard all of them. We don't check // that user shardings are consistent, because such check is already // done by HLO verifier. const HloInstruction* sharded_inst = nullptr; auto related_instructions = get_related_instructions(instruction); for (auto inst : related_instructions) { if (inst->has_sharding()) { sharded_inst = inst; break; } } if (sharded_inst != nullptr) { // Set the same sharding to all the other related instructions. for (auto inst : related_instructions) { inst->copy_sharding(sharded_inst); } } if (instruction->opcode() == HloOpcode::kWhile) { computation_map[instruction->while_body()] = instruction; } else { for (HloComputation* c : instruction->called_computations()) { computation_map[c] = instruction; } } } } } // Collect all pre-sharded instructions as we aren't allowed to modify their // sharding. absl::flat_hash_set<const HloInstruction*> provided_shardings; for (const HloComputation* computation : module->computations(execution_threads)) { for (const HloInstruction* inst : computation->instructions()) { if (inst->has_sharding() && inst != module->entry_computation()->root_instruction() && inst->opcode() != HloOpcode::kParameter && !inst->sharding().IsUnknown()) { provided_shardings.insert(inst); } } } if (!allow_spmd_sharding_propagation_to_output_ && (!module->entry_computation()->root_instruction()->has_sharding() || !module->entry_computation() ->root_instruction() ->sharding() .IsUnknown())) { // Consider the root instruction of the entry module as one with provided // sharding as its sharding have to match with the one expected by the host. provided_shardings.insert(module->entry_computation()->root_instruction()); } if (!allow_spmd_sharding_propagation_to_parameters_) { for (auto param : module->entry_computation()->parameter_instructions()) { if (param->has_sharding() && !param->sharding().IsUnknown()) { provided_shardings.insert(param); } } } // Replace all unknown shardings with replicated sharding for propagation. for (HloComputation* computation : module->computations(execution_threads)) { auto instructions = computation->MakeInstructionPostOrder(); for (auto it = instructions.rbegin(); it != instructions.rend(); ++it) { HloInstruction* instruction = *it; if (instruction->has_sharding() && instruction->sharding().IsUnknown()) { instruction->set_sharding( HloSharding::Replicate(instruction->sharding().metadata())); } } } // Iterate to a fixpoint that is guaranteed to be reached because we only // strictly improve the sharding of the graph and it can't be improved // indefinitely. int64_t iterations = 0; std::unique_ptr<CallGraph> call_graph = CallGraph::Build(module); auto run_to_fix_point = [&](int64_t aggressiveness, bool propagate_shard_group) { absl::flat_hash_set<const HloInstruction*> already_inferred_from_shard_group; absl::flat_hash_set<const HloInstruction*> already_inferred_from_operands; absl::flat_hash_set<const HloInstruction*> already_inferred_from_users; bool changed_last_iter = true; const bool may_merge_partial = is_spmd_ && aggressiveness > 0; while (changed_last_iter) { changed_last_iter = false; int64_t inferred_from_shard_group_counter = 0; int64_t inferred_from_operand_counter = 0; int64_t inferred_from_user_counter = 0; int64_t instruction_counter = 0; int64_t already_sharded_counter = 0; for (const HloComputation* computation : module->computations(execution_threads)) { VLOG(2) << "Consider computation: " << computation->name(); std::vector<HloInstruction*> instructions = computation->MakeInstructionPostOrder(); instruction_counter += instructions.size(); already_sharded_counter += absl::c_count_if( instructions, [](const HloInstruction* inst) { return inst->has_sharding(); }); auto clear_cache = [&](HloInstruction* hlo, HloInstruction* hlo_for_users = nullptr) { for (auto operand : hlo->operands()) { already_inferred_from_users.erase(operand); } if (hlo_for_users == nullptr) { hlo_for_users = hlo; } for (auto user : hlo_for_users->users()) { already_inferred_from_operands.erase(user); // If the user has called computations, then the parameter // instructions of these called computations are also removed from // already_inferred_from_operands. for (auto c : user->called_computations()) { for (auto parameter : c->parameter_instructions()) { already_inferred_from_operands.erase(parameter); } } } if (instruction_to_shard_group_id.contains(hlo)) { const int64_t shard_group_id = instruction_to_shard_group_id.at(hlo); const absl::flat_hash_set<HloInstruction*>& shard_group = shard_group_id_to_shard_as_group.contains(shard_group_id) ? shard_group_id_to_shard_as_group.at(shard_group_id) : shard_group_id_to_shard_like_group.at(shard_group_id); for (HloInstruction* member : shard_group) { if (member != hlo) { already_inferred_from_shard_group.erase(member); } } } }; // 1. Iterate the shard groups to take shardings from instructions of // the same group. if (propagate_shard_group) { for (HloInstruction* instruction : instructions) { if (already_inferred_from_shard_group.contains(instruction)) { continue; } if (!instruction_to_shard_group_id.contains(instruction)) { continue; } const int64_t shard_group_id = instruction_to_shard_group_id.at(instruction); const absl::flat_hash_set<HloInstruction*>& shard_group = shard_group_id_to_shard_as_group.contains(shard_group_id) ? shard_group_id_to_shard_as_group.at(shard_group_id) : shard_group_id_to_shard_like_group.at(shard_group_id); if (provided_shardings.contains(instruction)) { if (!may_merge_partial) { continue; } auto it = unspecified_dims.find(instruction); if (it != unspecified_dims.end() && InferUnspecifiedDimsFromShardGroup(instruction, it->second, shard_group)) { ++inferred_from_shard_group_counter; VLOG(2) << "Refined partial sharding (shard group): " << instruction->ToString(); clear_cache(instruction); already_inferred_from_shard_group.insert(instruction); changed_last_iter = true; } continue; } already_inferred_from_shard_group.insert(instruction); if (InferShardingFromShardGroup(instruction, computation_map, aggressiveness, shard_group)) { ++inferred_from_shard_group_counter; any_changed = true; VLOG(2) << "Add sharding (shard group): " << instruction->ToString(); absl::flat_hash_set<HloInstruction*> changed_in_comp_prop; maybe_computation_propagation(instruction, &changed_in_comp_prop); clear_cache(instruction); for (auto hlo : changed_in_comp_prop) { clear_cache(hlo); } changed_last_iter = true; } } } // 2. Iterate the HLO graph in post order taking shardings from // operands. for (HloInstruction* instruction : instructions) { if (already_inferred_from_operands.contains(instruction)) { continue; } if (provided_shardings.contains(instruction)) { if (!may_merge_partial) { continue; } auto it = unspecified_dims.find(instruction); HloInstruction* man_conversion_op_after; if (it != unspecified_dims.end() && InferUnspecifiedDimsFromOperand(instruction, it->second, &man_conversion_op_after)) { ++inferred_from_operand_counter; VLOG(2) << "Refined partial sharding (forward-pass): " << instruction->ToString(); clear_cache(instruction, man_conversion_op_after); already_inferred_from_operands.insert(instruction); changed_last_iter = true; } continue; } already_inferred_from_operands.insert(instruction); if (InferShardingFromOperands(instruction, computation_map, aggressiveness, *call_graph, execution_threads)) { ++inferred_from_operand_counter; any_changed = true; VLOG(2) << "Add sharding (forward-pass): " << instruction->ToString(); absl::flat_hash_set<HloInstruction*> changed_in_comp_prop; maybe_computation_propagation(instruction, &changed_in_comp_prop); clear_cache(instruction); for (auto hlo : changed_in_comp_prop) { clear_cache(hlo); } changed_last_iter = true; } } // 3. Iterate the HLO graph in reverse post order taking shardings from // users. for (auto it = instructions.rbegin(); it != instructions.rend(); ++it) { if ((*it)->IsCustomCall("SPMDFullToShardShape") || (*it)->IsCustomCall("SPMDShardToFullShape")) { // The manual conversion op is processed together with the sharding // op before it. If the conversion op is removed from cache, the // sharding op should also be removed. if (!already_inferred_from_users.contains(*it)) { already_inferred_from_users.erase((*it)->operand(0)); } } if (already_inferred_from_users.contains(*it)) { continue; } if (provided_shardings.contains(*it)) { if (!may_merge_partial) { continue; } auto uit = unspecified_dims.find(*it); HloInstruction* man_conversion_op_after; if (uit != unspecified_dims.end() && InferUnspecifiedDimsFromUsers( *it, uit->second, aggressiveness, is_spmd_, &man_conversion_op_after, *call_graph)) { ++inferred_from_user_counter; VLOG(2) << "Refined partial sharding (backward-pass): " << (*it)->ToString(); clear_cache(*it, man_conversion_op_after); already_inferred_from_users.insert(*it); if (man_conversion_op_after != nullptr) { already_inferred_from_users.insert(man_conversion_op_after); } changed_last_iter = true; } continue; } already_inferred_from_users.insert(*it); if (InferShardingFromUsers(*it, computation_map, aggressiveness, is_spmd_, sharding_helper_.get(), *call_graph)) { ++inferred_from_user_counter; any_changed = true; VLOG(2) << "Add sharding (backward-pass): " << (*it)->ToString(); absl::flat_hash_set<HloInstruction*> changed_in_comp_prop; maybe_computation_propagation(*it, &changed_in_comp_prop); clear_cache(*it); for (auto hlo : changed_in_comp_prop) { clear_cache(hlo); } changed_last_iter = true; } } } VLOG(1) << "Sharding propagation iteration " << iterations << ";" << "\n total instructions: " << instruction_counter << "\n instructions already sharded: " << already_sharded_counter << "\n shardings inferred from shard group: " << inferred_from_shard_group_counter << "\n shardings inferred from operands: " << inferred_from_operand_counter << "\n shardings inferred from users: " << inferred_from_user_counter << "\n aggressiveness: " << aggressiveness; ++iterations; } return absl::OkStatus(); }; for (int64_t aggressiveness = 0; aggressiveness < 4; ++aggressiveness) { TF_RETURN_IF_ERROR( run_to_fix_point(aggressiveness, /*propagate_shard_group=*/true)); } // Align the shardings from the same shard_as group so that they will adopt // the same sharding. for (const auto& [shard_as_group_id, shard_as_group] : shard_group_id_to_shard_as_group) { // If all the inferred shardings of the instructions from the same shard // group are compatible with each other, then we will merge all of them to // get the most specific sharding. If some of them are not compatible, then // it will just choose the a random sharding among them(say the first one), // with the guarantee that the defaultly chosen sharding will not be from a // ShardBarrierFrom op if there is one within the ShardAs group. HloSharding default_sharding = HloSharding::Replicate(); std::vector<HloSharding> shardings; for (HloInstruction* instruction : shard_as_group) { if (instruction->has_sharding()) { shardings.push_back(instruction->sharding()); if (!instruction->IsCustomCall(spmd::kShardBarrierFrom) && default_sharding.IsReplicated()) { default_sharding = instruction->sharding(); } } } HloSharding common_sharding = hlo_sharding_util::FindCommonSharding(shardings, default_sharding); VLOG(2) << "Aligning shard group: " << shard_as_group_id << " to sharding:" << common_sharding.ToString(); for (HloInstruction* member : shard_as_group) { if (member->IsCustomCall(spmd::kShardBarrierTo)) { continue; } if (provided_shardings.contains(member)) { auto it = unspecified_dims.find(member); if (it != unspecified_dims.end()) { HloSharding partial_replicated = hlo_sharding_util::PartiallyReplicateTiledShardingOnAllDimsExcept( common_sharding, it->second); HloSharding sharding = member->sharding(); if (hlo_sharding_util::MergeShardingIfCompatible( partial_replicated, sharding.NumTiles() + 1, &sharding)) { member->set_sharding(sharding); } } } member->set_sharding(common_sharding); } } // If a ShardBarrierFrom custom-call op is in a shard as group, and relay // the shard as sharding to its original op, do not relay shardings for // ShardbarrierTo op. Then run sharding propagation once more at highest // aggressiveness without propagating shard group. for (HloComputation* computation : module->computations(execution_threads)) { for (HloInstruction* instruction : computation->instructions()) { if (instruction->IsCustomCall(spmd::kShardBarrierFrom) && instruction_to_shard_group_id.contains(instruction) && shard_group_id_to_shard_as_group.contains( instruction_to_shard_group_id.at(instruction))) { HloSharding sharding = instruction->sharding(); hlo_sharding_util::MergeShardingIfCompatible( instruction->mutable_operand(0)->sharding(), sharding.NumTiles(), &sharding); instruction->mutable_operand(0)->set_sharding(std::move(sharding)); } } } TF_RETURN_IF_ERROR( run_to_fix_point(/*aggressiveness=*/3, /*propagate_shard_group=*/false)); // Post-process to remove all "shard-barrier-from" and "shard-barrier-to" // custom-calls. for (HloComputation* computation : module->computations(execution_threads)) { for (HloInstruction* instruction : computation->instructions()) { // If a ShardBarrierFrom custom-call op is in a shard as group, and relay // the shard as sharding to its original op, do not relay shardings for // ShardbarrierTo op. if (instruction->IsCustomCall(spmd::kShardBarrierFrom) && instruction_to_shard_group_id.contains(instruction) && shard_group_id_to_shard_as_group.contains( instruction_to_shard_group_id.at(instruction))) { HloSharding sharding = instruction->sharding(); hlo_sharding_util::MergeShardingIfCompatible( instruction->mutable_operand(0)->sharding(), sharding.NumTiles(), &sharding); instruction->mutable_operand(0)->set_sharding(std::move(sharding)); } if (instruction->IsCustomCall(spmd::kShardBarrierFrom) || instruction->IsCustomCall(spmd::kShardBarrierTo)) { TF_ASSIGN_OR_RETURN(std::ignore, computation->ReplaceInstruction( instruction, instruction->mutable_operand(0), /*preserve_sharding=*/false, /*relay_control_dependency=*/false, /*remove_unused_operands=*/false)); } } } // Post-process for CSE prevention. if (cse_prevention_only_) { for (auto computation : module->computations(execution_threads)) { for (auto instruction : computation->instructions()) { if (!instruction->has_sharding()) { continue; } if (IsCSEPreventionTarget(instruction) && instruction->has_sharding()) { if (!(*original_sharding).contains(instruction)) { // Mark the propagated sharding as for CSE prevention. instruction->set_sharding( SetCSEPreventionSharding(instruction->sharding())); } continue; } auto it = (*original_sharding).find(instruction); if (it != (*original_sharding).end()) { // Revert sharding. instruction->set_sharding(it->second); } else { // Clear sharding. instruction->clear_sharding(); } } } } HloInstruction* root_instruction = module->entry_computation()->root_instruction(); if (saved_root_shardings.size() == allow_spmd_sharding_propagation_to_output_vector_.size() && root_instruction->has_sharding()) { HloSharding root_sharding = root_instruction->sharding(); for (int i = 0; i < saved_root_shardings.size(); ++i) { if (!allow_spmd_sharding_propagation_to_output_vector_[i] && !saved_root_shardings[i].IsUnknown()) { root_sharding.tuple_elements()[i] = saved_root_shardings[i]; } } root_instruction->set_sharding(std::move(root_sharding)); } auto params = module->entry_computation()->parameter_instructions(); if (allow_spmd_sharding_propagation_to_parameters_) { if (allow_spmd_sharding_propagation_to_parameters_vector_.size() == params.size()) { for (int64_t i = 0; i < params.size(); ++i) { if (!allow_spmd_sharding_propagation_to_parameters_vector_[i]) { if (saved_parameter_shardings.contains(i) && !saved_parameter_shardings.at(i).IsUnknown()) { params[i]->set_sharding(saved_parameter_shardings.at(i)); } else { params[i]->clear_sharding(); } } } } else if (params.size() == 1 && saved_parameter_shardings.size() == 1 && params[0]->shape().IsTuple() && params[0]->shape().tuple_shapes_size() == allow_spmd_sharding_propagation_to_parameters_vector_ .size()) { // There is a single parameter which is a tuple with many elements. HloSharding param_sharding = params[0]->sharding(); for (int64_t i = 0; i < params[0]->shape().tuple_shapes_size(); ++i) { HloSharding saved_subsharding = saved_parameter_shardings.at(0).GetSubSharding(params[0]->shape(), {i}); if (!allow_spmd_sharding_propagation_to_parameters_vector_[i] && !saved_subsharding.IsUnknown()) { param_sharding.tuple_elements()[i] = saved_subsharding; } } params[0]->set_sharding(std::move(param_sharding)); } } // Replicate the parameter/output sharding if the propagated sharding does not // evenly partition the parameter/output. std::function<bool(const Shape&, const HloSharding&)> evenly_partitions = [&evenly_partitions](const Shape& shape, const HloSharding& sharding) -> bool { if (!sharding.IsTiled()) { return true; } if (sharding.IsTileMaximal()) { return sharding.IsReplicated(); } if (sharding.IsTuple()) { for (int64_t i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { if (!evenly_partitions(ShapeUtil::GetTupleElementShape(shape, i), sharding.GetSubSharding(shape, {i}))) { return false; } } } for (int64_t i = 0; i < shape.dimensions_size(); ++i) { if (shape.dimensions(i) % sharding.tile_assignment().dim(i) != 0) { return false; } } return true; }; if (allow_spmd_sharding_propagation_to_output_ && root_instruction->has_sharding()) { if (root_instruction->shape().IsTuple() && allow_spmd_sharding_propagation_to_output_vector_.size() == root_instruction->shape().tuple_shapes_size()) { // The output shape is a tuple and sharding propagation is allowed for at // least one of its elements. HloSharding root_sharding = root_instruction->sharding(); for (int64_t i = 0; i < root_instruction->shape().tuple_shapes_size(); ++i) { if (allow_spmd_sharding_propagation_to_output_vector_[i] && !evenly_partitions(root_instruction->shape().tuple_shapes(i), root_sharding.tuple_elements()[i])) { root_sharding.tuple_elements()[i] = HloSharding::Replicate(); } } root_instruction->set_sharding(std::move(root_sharding)); } else if (!root_instruction->shape().IsTuple()) { // The output shape is not tuple and sharding propagation is allowed. if (!evenly_partitions(root_instruction->shape(), root_instruction->sharding())) { root_instruction->set_sharding(HloSharding::Replicate()); } } } if (allow_spmd_sharding_propagation_to_parameters_) { // Sharding propagation is allowed for at least one parameter. if (allow_spmd_sharding_propagation_to_parameters_vector_.size() == params.size()) { for (int64_t i = 0; i < params.size(); ++i) { if (params[i]->has_sharding() && allow_spmd_sharding_propagation_to_parameters_vector_[i] && !evenly_partitions(params[i]->shape(), params[i]->sharding())) { params[i]->set_sharding(HloSharding::Replicate()); } } } else if (params.size() == 1 && params[0]->shape().IsTuple() && params[0]->has_sharding() && params[0]->shape().tuple_shapes_size() == allow_spmd_sharding_propagation_to_parameters_vector_ .size()) { HloSharding param_sharding = params[0]->sharding(); for (int64_t i = 0; i < params[0]->shape().tuple_shapes_size(); ++i) { if (allow_spmd_sharding_propagation_to_parameters_vector_[i] && !evenly_partitions( ShapeUtil::GetSubshapeOneIndex(params[0]->shape(), i), params[0]->sharding().GetSubSharding(params[0]->shape(), {i}))) { param_sharding.tuple_elements()[i] = HloSharding::Replicate(); } } params[0]->set_sharding(std::move(param_sharding)); } } TF_RETURN_IF_ERROR( hlo_sharding_util::CanonicalizeLayoutAfterShardingPropagation( module, allow_spmd_sharding_propagation_to_output_, allow_spmd_sharding_propagation_to_parameters_)); VLOG(1) << "Sharding propagation completed after " << iterations << " iterations"; return any_changed; } absl::call_once(did_registration, [] { RegisterCustomCallPartitioner( spmd::kShardBarrierFrom, std::make_unique<spmd::ShardBarrierFromPartitioner>()); RegisterCustomCallPartitioner( spmd::kShardBarrierTo, std::make_unique<spmd::ShardBarrierToPartitioner>()); }); VLOG(5) << "Shard-As group " << shard_group_id << " contains:"; VLOG(5) << " " << instruction->ToString(); VLOG(5) << "Shard-Like group " << shard_group_id << " contains:"; VLOG(5) << " " << instruction->ToString(); auto is_same_sized_tuple = [](HloModule* module, int64_t size) { if (module->entry_computation()->num_parameters() != 1) { return false; } HloInstruction* param = module->entry_computation()->parameter_instruction(0); return param->shape().IsTuple() && size == param->shape().tuple_shapes_size(); }; auto get_related_instructions = [this](HloInstruction* inst) { if (inst->opcode() == HloOpcode::kWhile) { return std::vector<HloInstruction*>{ inst, inst->while_body()->root_instruction(), inst->while_body()->parameter_instruction(0), inst->while_condition()->parameter_instruction(0)}; } else if (inst->opcode() == HloOpcode::kConditional) { const auto& called_computations = inst->called_computations(); std::vector<HloInstruction*> comps; comps.reserve(called_computations.size() + 1); comps.push_back(inst); for (HloComputation* c : called_computations) { comps.push_back(c->root_instruction()); } return comps; } else if (inst->opcode() == HloOpcode::kCustomCall) { if (sharding_helper_ && sharding_helper_->IsCustomCallShardable(inst)) { return sharding_helper_->GetRelatedInstructions(inst); } else { return std::vector<HloInstruction*>{}; } } else if (inst->opcode() == HloOpcode::kCall) { HloComputation* callee = inst->called_computations().front(); return std::vector<HloInstruction*>{inst, callee->root_instruction()}; } else { CHECK(false); } }; [&](HloInstruction* instruction, absl::flat_hash_set<HloInstruction*>* changed) { auto propagate_to_instruction = [&](HloInstruction* search_inst) { auto related_instructions = get_related_instructions(search_inst); if (absl::c_count(related_instructions, instruction)) { for (HloInstruction* inst : related_instructions) { if (!inst->has_sharding() || inst->sharding() != instruction->sharding()) { VLOG(2) << "Add computation sharding: " << inst->name() << " " << instruction->sharding().ToString(); inst->copy_sharding(instruction); changed->insert(inst); maybe_computation_propagation(inst, changed); } } } }; if (instruction->opcode() == HloOpcode::kConditional || instruction->opcode() == HloOpcode::kWhile || instruction->opcode() == HloOpcode::kCustomCall || instruction->opcode() == HloOpcode::kCall) { propagate_to_instruction(instruction); } if (instruction->opcode() == HloOpcode::kParameter || instruction->parent()->root_instruction() == instruction) { auto it = computation_map.find(instruction->parent()); if (it != computation_map.end()) { propagate_to_instruction(it->second); } } }; auto propagate_to_instruction = [&](HloInstruction* search_inst) { auto related_instructions = get_related_instructions(search_inst); if (absl::c_count(related_instructions, instruction)) { for (HloInstruction* inst : related_instructions) { if (!inst->has_sharding() || inst->sharding() != instruction->sharding()) { VLOG(2) << "Add computation sharding: " << inst->name() << " " << instruction->sharding().ToString(); inst->copy_sharding(instruction); changed->insert(inst); maybe_computation_propagation(inst, changed); } } } }; VLOG(2) << "Add computation sharding: " << inst->name() auto run_to_fix_point = [&](int64_t aggressiveness, bool propagate_shard_group) { absl::flat_hash_set<const HloInstruction*> already_inferred_from_shard_group; absl::flat_hash_set<const HloInstruction*> already_inferred_from_operands; absl::flat_hash_set<const HloInstruction*> already_inferred_from_users; bool changed_last_iter = true; const bool may_merge_partial = is_spmd_ && aggressiveness > 0; while (changed_last_iter) { changed_last_iter = false; int64_t inferred_from_shard_group_counter = 0; int64_t inferred_from_operand_counter = 0; int64_t inferred_from_user_counter = 0; int64_t instruction_counter = 0; int64_t already_sharded_counter = 0; for (const HloComputation* computation : module->computations(execution_threads)) { VLOG(2) << "Consider computation: " << computation->name(); std::vector<HloInstruction*> instructions = computation->MakeInstructionPostOrder(); instruction_counter += instructions.size(); already_sharded_counter += absl::c_count_if( instructions, [](const HloInstruction* inst) { return inst->has_sharding(); }); auto clear_cache = [&](HloInstruction* hlo, HloInstruction* hlo_for_users = nullptr) { for (auto operand : hlo->operands()) { already_inferred_from_users.erase(operand); } if (hlo_for_users == nullptr) { hlo_for_users = hlo; } for (auto user : hlo_for_users->users()) { already_inferred_from_operands.erase(user); // If the user has called computations, then the parameter // instructions of these called computations are also removed from // already_inferred_from_operands. for (auto c : user->called_computations()) { for (auto parameter : c->parameter_instructions()) { already_inferred_from_operands.erase(parameter); } } } if (instruction_to_shard_group_id.contains(hlo)) { const int64_t shard_group_id = instruction_to_shard_group_id.at(hlo); const absl::flat_hash_set<HloInstruction*>& shard_group = shard_group_id_to_shard_as_group.contains(shard_group_id) ? shard_group_id_to_shard_as_group.at(shard_group_id) : shard_group_id_to_shard_like_group.at(shard_group_id); for (HloInstruction* member : shard_group) { if (member != hlo) { already_inferred_from_shard_group.erase(member); } } } }; // 1. Iterate the shard groups to take shardings from instructions of // the same group. if (propagate_shard_group) { for (HloInstruction* instruction : instructions) { if (already_inferred_from_shard_group.contains(instruction)) { continue; } if (!instruction_to_shard_group_id.contains(instruction)) { continue; } const int64_t shard_group_id = instruction_to_shard_group_id.at(instruction); const absl::flat_hash_set<HloInstruction*>& shard_group = shard_group_id_to_shard_as_group.contains(shard_group_id) ? shard_group_id_to_shard_as_group.at(shard_group_id) : shard_group_id_to_shard_like_group.at(shard_group_id); if (provided_shardings.contains(instruction)) { if (!may_merge_partial) { continue; } auto it = unspecified_dims.find(instruction); if (it != unspecified_dims.end() && InferUnspecifiedDimsFromShardGroup(instruction, it->second, shard_group)) { ++inferred_from_shard_group_counter; VLOG(2) << "Refined partial sharding (shard group): " << instruction->ToString(); clear_cache(instruction); already_inferred_from_shard_group.insert(instruction); changed_last_iter = true; } continue; } already_inferred_from_shard_group.insert(instruction); if (InferShardingFromShardGroup(instruction, computation_map, aggressiveness, shard_group)) { ++inferred_from_shard_group_counter; any_changed = true; VLOG(2) << "Add sharding (shard group): " << instruction->ToString(); absl::flat_hash_set<HloInstruction*> changed_in_comp_prop; maybe_computation_propagation(instruction, &changed_in_comp_prop); clear_cache(instruction); for (auto hlo : changed_in_comp_prop) { clear_cache(hlo); } changed_last_iter = true; } } } // 2. Iterate the HLO graph in post order taking shardings from // operands. for (HloInstruction* instruction : instructions) { if (already_inferred_from_operands.contains(instruction)) { continue; } if (provided_shardings.contains(instruction)) { if (!may_merge_partial) { continue; } auto it = unspecified_dims.find(instruction); HloInstruction* man_conversion_op_after; if (it != unspecified_dims.end() && InferUnspecifiedDimsFromOperand(instruction, it->second, &man_conversion_op_after)) { ++inferred_from_operand_counter; VLOG(2) << "Refined partial sharding (forward-pass): " << instruction->ToString(); clear_cache(instruction, man_conversion_op_after); already_inferred_from_operands.insert(instruction); changed_last_iter = true; } continue; } already_inferred_from_operands.insert(instruction); if (InferShardingFromOperands(instruction, computation_map, aggressiveness, *call_graph, execution_threads)) { ++inferred_from_operand_counter; any_changed = true; VLOG(2) << "Add sharding (forward-pass): " << instruction->ToString(); absl::flat_hash_set<HloInstruction*> changed_in_comp_prop; maybe_computation_propagation(instruction, &changed_in_comp_prop); clear_cache(instruction); for (auto hlo : changed_in_comp_prop) { clear_cache(hlo); } changed_last_iter = true; } } // 3. Iterate the HLO graph in reverse post order taking shardings from // users. for (auto it = instructions.rbegin(); it != instructions.rend(); ++it) { if ((*it)->IsCustomCall("SPMDFullToShardShape") || (*it)->IsCustomCall("SPMDShardToFullShape")) { // The manual conversion op is processed together with the sharding // op before it. If the conversion op is removed from cache, the // sharding op should also be removed. if (!already_inferred_from_users.contains(*it)) { already_inferred_from_users.erase((*it)->operand(0)); } } if (already_inferred_from_users.contains(*it)) { continue; } if (provided_shardings.contains(*it)) { if (!may_merge_partial) { continue; } auto uit = unspecified_dims.find(*it); HloInstruction* man_conversion_op_after; if (uit != unspecified_dims.end() && InferUnspecifiedDimsFromUsers( *it, uit->second, aggressiveness, is_spmd_, &man_conversion_op_after, *call_graph)) { ++inferred_from_user_counter; VLOG(2) << "Refined partial sharding (backward-pass): " << (*it)->ToString(); clear_cache(*it, man_conversion_op_after); already_inferred_from_users.insert(*it); if (man_conversion_op_after != nullptr) { already_inferred_from_users.insert(man_conversion_op_after); } changed_last_iter = true; } continue; } already_inferred_from_users.insert(*it); if (InferShardingFromUsers(*it, computation_map, aggressiveness, is_spmd_, sharding_helper_.get(), *call_graph)) { ++inferred_from_user_counter; any_changed = true; VLOG(2) << "Add sharding (backward-pass): " << (*it)->ToString(); absl::flat_hash_set<HloInstruction*> changed_in_comp_prop; maybe_computation_propagation(*it, &changed_in_comp_prop); clear_cache(*it); for (auto hlo : changed_in_comp_prop) { clear_cache(hlo); } changed_last_iter = true; } } } VLOG(1) << "Sharding propagation iteration " << iterations << ";" << "\n total instructions: " << instruction_counter << "\n instructions already sharded: " << already_sharded_counter << "\n shardings inferred from shard group: " << inferred_from_shard_group_counter << "\n shardings inferred from operands: " << inferred_from_operand_counter << "\n shardings inferred from users: " << inferred_from_user_counter << "\n aggressiveness: " << aggressiveness; ++iterations; } return absl::OkStatus(); }; VLOG(2) << "Consider computation: " << computation->name(); auto clear_cache = [&](HloInstruction* hlo, HloInstruction* hlo_for_users = nullptr) { for (auto operand : hlo->operands()) { already_inferred_from_users.erase(operand); } if (hlo_for_users == nullptr) { hlo_for_users = hlo; } for (auto user : hlo_for_users->users()) { already_inferred_from_operands.erase(user); // If the user has called computations, then the parameter // instructions of these called computations are also removed from // already_inferred_from_operands. for (auto c : user->called_computations()) { for (auto parameter : c->parameter_instructions()) { already_inferred_from_operands.erase(parameter); } } } if (instruction_to_shard_group_id.contains(hlo)) { const int64_t shard_group_id = instruction_to_shard_group_id.at(hlo); const absl::flat_hash_set<HloInstruction*>& shard_group = shard_group_id_to_shard_as_group.contains(shard_group_id) ? shard_group_id_to_shard_as_group.at(shard_group_id) : shard_group_id_to_shard_like_group.at(shard_group_id); for (HloInstruction* member : shard_group) { if (member != hlo) { already_inferred_from_shard_group.erase(member); } } } }; VLOG(2) << "Refined partial sharding (shard group): " VLOG(2) << "Add sharding (shard group): " VLOG(2) << "Refined partial sharding (forward-pass): " VLOG(2) << "Add sharding (forward-pass): " VLOG(2) << "Refined partial sharding (backward-pass): " VLOG(2) << "Add sharding (backward-pass): " << (*it)->ToString(); VLOG(1) << "Sharding propagation iteration " << iterations << ";" VLOG(2) << "Aligning shard group: " << shard_as_group_id [&evenly_partitions](const Shape& shape, const HloSharding& sharding) -> bool { if (!sharding.IsTiled()) { return true; } if (sharding.IsTileMaximal()) { return sharding.IsReplicated(); } if (sharding.IsTuple()) { for (int64_t i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { if (!evenly_partitions(ShapeUtil::GetTupleElementShape(shape, i), sharding.GetSubSharding(shape, {i}))) { return false; } } } for (int64_t i = 0; i < shape.dimensions_size(); ++i) { if (shape.dimensions(i) % sharding.tile_assignment().dim(i) != 0) { return false; } } return true; }; VLOG(1) << "Sharding propagation completed after " << iterations
#include "xla/service/sharding_propagation.h" #include <ostream> #include <string> #include <utility> #include <vector> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/log/check.h" #include "absl/log/log.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/ir/hlo_op_metadata.h" #include "xla/hlo/ir/hlo_sharding.h" #include "xla/hlo/transforms/hlo_constant_splitter.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/protobuf_util.h" #include "xla/service/hlo_dce.h" #include "xla/service/hlo_parser.h" #include "xla/tests/hlo_test_base.h" #include "xla/util.h" #include "xla/xla_data.pb.h" #include "tsl/platform/statusor.h" TEST_F(ShardingPropagationTest, PropagateShardLikeSameSharding) { const char* const hlo_string = R"( HloModule module %add { %lhs = s32[] parameter(0) %rhs = s32[] parameter(1) ROOT %add = s32[] add(%lhs, %rhs) } ENTRY %entry { p.0 = s32[16,16] parameter(0), sharding={devices=[4,2]0,1,2,3,4,5,6,7} p.1 = s32[16,16] parameter(1) add.1 = s32[16,16] add(p.0, p.0) sharding.1 = s32[16,16] custom-call(add.1), custom_call_target="Sharding", sharding={unknown shard_like 0} init = s32[] constant(0) reduce.1 = s32[] reduce(add.1, init), dimensions={0,1}, to_apply=%add add.2 = s32[16,16] add(p.1, p.1) sharding.2 = s32[16,16] custom-call(add.2), custom_call_target="Sharding", sharding={unknown shard_like 0} reduce.2 = s32[] reduce(add.2, init), dimensions={0,1}, to_apply=%add ROOT mul = s32[] multiply(reduce.1, reduce.2) })"; TF_ASSERT_OK_AND_ASSIGN(auto module, ParseAndReturnVerifiedModule(hlo_string)); TF_ASSERT_OK_AND_ASSIGN( bool changed, ShardingPropagation( /*is_spmd=*/true, /*propagate_metadata=*/true, /*allow_spmd_sharding_propagation_to_output=*/{true}, /*allow_spmd_sharding_propagation_to_parameters=*/{false, false}) .Run(module.get())); EXPECT_TRUE(changed); XLA_VLOG_LINES(1, module->ToString()); // Check dangling sharding custom-call can be removed by DCE after // propagation. auto* add_1 = FindInstruction(module.get(), "add.1"); ASSERT_NE(add_1, nullptr); auto* add_2 = FindInstruction(module.get(), "add.2"); ASSERT_NE(add_2, nullptr); // Check sharding is correctly propagated. EXPECT_EQ(add_1->sharding(), add_2->sharding()); }
ShardingPropagationTest_PropagateToParametersFull1
xla/service/sharding_propagation_test.cc
std::optional<HloSharding> ReturnImprovedSharding( HloSharding sharding, HloInstruction* instruction, bool may_combine_partial_sharding, bool allow_aggressive_resharding = false) { return hlo_sharding_util::ReturnImprovedShardingImpl( std::move(sharding), instruction->has_sharding() ? &instruction->sharding() : nullptr, instruction->shape(), may_combine_partial_sharding, allow_aggressive_resharding); } std::optional<HloSharding> ReturnImprovedSubSharding( HloSharding sharding, HloInstruction* instruction, const ShapeIndex& index, bool may_combine_partial_sharding, bool allow_aggressive_resharding = false) { if (instruction->has_sharding()) { const HloSharding to_improved = instruction->sharding().GetSubSharding(instruction->shape(), index); return hlo_sharding_util::ReturnImprovedShardingImpl( std::move(sharding), &to_improved, ShapeUtil::GetSubshape(instruction->shape(), index), may_combine_partial_sharding, allow_aggressive_resharding); } else { return hlo_sharding_util::ReturnImprovedShardingImpl( std::move(sharding), nullptr, ShapeUtil::GetSubshape(instruction->shape(), index), may_combine_partial_sharding, allow_aggressive_resharding); } } bool MaybeImproveInstructionSharding(HloSharding sharding, HloInstruction* instruction, bool may_combine_partial_sharding, bool allow_aggressive_resharding = false) { if (auto new_sharding = ReturnImprovedSharding( std::move(sharding), instruction, may_combine_partial_sharding, allow_aggressive_resharding)) { instruction->set_sharding(std::move(*new_sharding)); return true; } return false; } bool MaybeImproveInstructionSubSharding( HloSharding sharding, HloInstruction* instruction, const ShapeIndex& index, bool may_combine_partial_sharding, bool allow_aggressive_resharding = false) { if (instruction->shape().IsTuple()) { if (auto new_sub_sharding = ReturnImprovedSubSharding( std::move(sharding), instruction, index, may_combine_partial_sharding, allow_aggressive_resharding)) { HloSharding new_sharding = instruction->has_sharding() ? instruction->sharding() : HloSharding::Single(instruction->shape(), HloSharding::Replicate()); ShapeTree<HloSharding> sharding_shape_tree = new_sharding.GetAsShapeTree(instruction->shape()); *sharding_shape_tree.mutable_element(index) = new_sub_sharding.value(); instruction->set_sharding(HloSharding::Tuple(sharding_shape_tree)); return true; } else { return false; } } CHECK(index.size() == 1 && index[0] == 0); return MaybeImproveInstructionSharding(std::move(sharding), instruction, may_combine_partial_sharding, allow_aggressive_resharding); } bool IsConvolutionKernelSmall(const HloInstruction* instruction) { CHECK_EQ(instruction->opcode(), HloOpcode::kConvolution); const HloInstruction* rhs = instruction->operand(1); const auto& dnums = instruction->convolution_dimension_numbers(); int64_t kernel_dim_prod = 1; int64_t output_dim_prod = 1; for (int64_t i = 0; i < dnums.input_spatial_dimensions().size(); ++i) { int64_t kernel_dim = rhs->shape().dimensions(dnums.kernel_spatial_dimensions(i)); kernel_dim_prod *= kernel_dim; int64_t output_dim = instruction->shape().dimensions(dnums.output_spatial_dimensions(i)); output_dim_prod *= output_dim; if (kernel_dim >= output_dim && (i < 2 || kernel_dim > 3 || kernel_dim_prod >= output_dim_prod)) { return false; } } return true; } bool IsPassthroughCustomOps(const HloInstruction* hlo) { if (hlo->IsCustomCall({"Sharding", "X64Combine", "LayoutConstraint"})) { return true; } if (hlo->operand_count() != 1 || !hlo->shape().IsArray() || !hlo->operand(0)->shape().IsArray() || hlo->operand(0)->shape().rank() != hlo->shape().rank()) { return false; } return hlo->IsCustomCall( {"ResizeNearest", "ResizeBilinear", "ResizeNearestGrad", "ResizeBilinearGrad", "Cholesky", host_memory_offload_annotations::kMoveToDeviceCustomCallTarget, host_memory_offload_annotations::kMoveToHostCustomCallTarget}); } const HloInstruction* PickRepresentativeOperand( const HloInstruction* instruction) { switch (instruction->opcode()) { case HloOpcode::kMap: case HloOpcode::kPad: case HloOpcode::kPower: case HloOpcode::kOptimizationBarrier: case HloOpcode::kReverse: case HloOpcode::kSlice: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: // For these opcodes the output sharding has to be determined by the // sharding of the first operand but we can only determine sharding based // on it if it already has a sharding. if (instruction->operand(0)->has_sharding()) { return instruction->operand(0); } return nullptr; case HloOpcode::kAbs: case HloOpcode::kAdd: case HloOpcode::kAnd: case HloOpcode::kAtan2: case HloOpcode::kBitcastConvert: case HloOpcode::kCeil: case HloOpcode::kClamp: case HloOpcode::kClz: case HloOpcode::kCompare: case HloOpcode::kComplex: case HloOpcode::kConcatenate: case HloOpcode::kConvert: case HloOpcode::kCopy: case HloOpcode::kCos: case HloOpcode::kAllGather: case HloOpcode::kAllReduce: case HloOpcode::kReduceScatter: case HloOpcode::kAllToAll: case HloOpcode::kCollectiveBroadcast: case HloOpcode::kCollectivePermute: case HloOpcode::kDivide: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kFloor: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kMultiply: case HloOpcode::kNegate: case HloOpcode::kNot: case HloOpcode::kOr: case HloOpcode::kPopulationCount: case HloOpcode::kReal: case HloOpcode::kReducePrecision: case HloOpcode::kRemainder: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kRsqrt: case HloOpcode::kSelect: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kTopK: case HloOpcode::kSort: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kSubtract: case HloOpcode::kStochasticConvert: case HloOpcode::kTan: case HloOpcode::kTanh: case HloOpcode::kWhile: case HloOpcode::kXor: { // For these opcodes the output sharding can be determined by any operand // so we find the operand with the most specific sharding. const HloInstruction* best_operand = nullptr; for (const HloInstruction* operand : instruction->operands()) { if (operand->has_sharding() && (best_operand == nullptr || hlo_sharding_util::IsShardingMoreSpecific( operand->sharding(), best_operand->sharding()))) { best_operand = operand; } } return best_operand; } case HloOpcode::kCustomCall: { if (IsPassthroughCustomOps(instruction)) { return instruction->operand(0); } return nullptr; } // There is no suitable operand for the rest of the opcodes. case HloOpcode::kAddDependency: case HloOpcode::kAfterAll: case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: case HloOpcode::kAllGatherStart: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduceStart: case HloOpcode::kAllReduceDone: case HloOpcode::kBatchNormGrad: case HloOpcode::kBatchNormInference: case HloOpcode::kBatchNormTraining: case HloOpcode::kBitcast: case HloOpcode::kBroadcast: case HloOpcode::kCall: case HloOpcode::kCholesky: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCollectivePermuteStart: case HloOpcode::kConditional: case HloOpcode::kConstant: case HloOpcode::kConvolution: case HloOpcode::kCopyDone: case HloOpcode::kCopyStart: case HloOpcode::kDomain: case HloOpcode::kDot: case HloOpcode::kDynamicSlice: case HloOpcode::kDynamicUpdateSlice: case HloOpcode::kDynamicReshape: case HloOpcode::kFft: case HloOpcode::kFusion: case HloOpcode::kGather: case HloOpcode::kGetTupleElement: case HloOpcode::kInfeed: case HloOpcode::kIota: case HloOpcode::kOutfeed: case HloOpcode::kParameter: case HloOpcode::kPartitionId: case HloOpcode::kRecv: case HloOpcode::kRecvDone: case HloOpcode::kReduce: case HloOpcode::kReduceWindow: case HloOpcode::kReplicaId: case HloOpcode::kReshape: case HloOpcode::kRng: case HloOpcode::kRngGetAndUpdateState: case HloOpcode::kRngBitGenerator: case HloOpcode::kScatter: case HloOpcode::kSelectAndScatter: case HloOpcode::kSend: case HloOpcode::kSendDone: case HloOpcode::kTranspose: case HloOpcode::kTriangularSolve: case HloOpcode::kTuple: case HloOpcode::kGetDimensionSize: case HloOpcode::kSetDimensionSize: return nullptr; } } bool SupportSpatialPartitioning( const HloInstruction* instruction, const ShardingPropagation::ComputationMap& computation_map, bool is_spmd, bool allow_spmd_sharding_propagation_to_output, bool allow_spmd_sharding_propagation_to_parameters, const CustomCallShardingHelper* sharding_helper) { const bool is_entry_root = instruction->parent() ->parent() ->entry_computation() ->root_instruction() == instruction; if (instruction->parent()->root_instruction() == instruction && computation_map.find(instruction->parent()) == computation_map.end() && !(is_entry_root && allow_spmd_sharding_propagation_to_output)) { // We don't support sharding the root instruction of a computation yet, // unless the computation is a while body. return false; } if (instruction->IsElementwise() && (instruction->opcode() != HloOpcode::kRng || is_spmd)) { return true; } switch (instruction->opcode()) { case HloOpcode::kBroadcast: case HloOpcode::kConcatenate: case HloOpcode::kConditional: case HloOpcode::kConstant: case HloOpcode::kConvolution: case HloOpcode::kOptimizationBarrier: case HloOpcode::kDot: case HloOpcode::kDynamicSlice: case HloOpcode::kDynamicUpdateSlice: case HloOpcode::kGather: case HloOpcode::kGetTupleElement: case HloOpcode::kInfeed: case HloOpcode::kIota: case HloOpcode::kPad: case HloOpcode::kReduceWindow: case HloOpcode::kReshape: case HloOpcode::kScatter: case HloOpcode::kSelectAndScatter: case HloOpcode::kSlice: case HloOpcode::kSort: case HloOpcode::kTranspose: case HloOpcode::kTuple: case HloOpcode::kWhile: case HloOpcode::kReduce: case HloOpcode::kRngBitGenerator: case HloOpcode::kAllReduce: case HloOpcode::kReduceScatter: return true; case HloOpcode::kParameter: return allow_spmd_sharding_propagation_to_parameters || computation_map.find(instruction->parent()) != computation_map.end(); case HloOpcode::kReverse: return is_spmd; case HloOpcode::kCustomCall: if (!is_spmd) { return false; } if (auto* partitioner = GetCustomCallPartitioner(instruction->custom_call_target())) { return partitioner->IsCustomCallShardable(instruction); } return (IsPassthroughCustomOps(instruction) || sharding_helper->IsCustomCallShardable(instruction)); default: return false; } } std::optional<HloSharding> LookaheadUserSharding(HloInstruction* instr, bool is_spmd, const CallGraph& call_graph) { if (instr->user_count() != 1) { return std::nullopt; } HloInstruction* current_user = instr->users()[0]; std::optional<HloSharding> sharding; std::vector<HloInstruction*> users_chain = {instr, current_user}; // Collect single user instructions along the way. while (!current_user->has_sharding()) { // Only consider single user chains. if (current_user->users().size() != 1) { users_chain.clear(); break; } current_user = current_user->users()[0]; users_chain.push_back(current_user); } // Early exit for unsupported cases. if (users_chain.empty()) { return std::nullopt; } for (int i = users_chain.size() - 1; i >= 1; --i) { HloInstruction* user = users_chain[i]; HloInstruction* current = users_chain[i - 1]; CHECK(user->has_sharding()); sharding = ShardingPropagation::GetShardingFromUser( *current, *user, INT64_MAX, is_spmd, call_graph, /*sharding_helper=*/nullptr); // We need to set the sharding to the instruction, because // GetShardingFromUser() interface uses sharding from the instruction // itself. It will be cleared out later. if (sharding.has_value() && i != 1) { current->set_sharding(*sharding); continue; } break; } // Clear the sharding of the middle instructions we set the sharding of // because they were unsharded. for (int i = 1; i < users_chain.size() - 1; ++i) { users_chain[i]->clear_sharding(); } return sharding; } bool InferGatherParallelShardingFromOperands( HloInstruction* instruction, const hlo_sharding_util::GatherScatterParallelDims& parallel_dims, bool may_combine_partial_sharding) { CHECK(DynCast<HloGatherInstruction>(instruction)); bool changed = false; auto aligned_operand_parallel_dims = hlo_sharding_util::IndexAlignedOperandParallelDims(parallel_dims); auto output_parallel_dims = hlo_sharding_util::GetGatherParallelOutputDims( *instruction, parallel_dims); // Infer output sharding from scatter operand sharding. if (hlo_sharding_util::IsSpatiallyPartitioned(instruction->operand(0))) { changed |= MaybeImproveInstructionSharding( hlo_sharding_util:: InferGatherScatterParallelShardingFromOperandSharding( instruction->operand(0)->sharding(), instruction->operand(0)->shape(), instruction->shape(), absl::MakeConstSpan(aligned_operand_parallel_dims), absl::MakeConstSpan(output_parallel_dims)), instruction, may_combine_partial_sharding); } // Infer output sharding from scatter indices sharding. if (hlo_sharding_util::IsSpatiallyPartitioned(instruction->operand(1))) { changed |= MaybeImproveInstructionSharding( hlo_sharding_util:: InferGatherScatterParallelShardingFromOperandSharding( instruction->operand(1)->sharding(), instruction->operand(1)->shape(), instruction->shape(), absl::MakeConstSpan(parallel_dims.indices_parallel_dims), absl::MakeConstSpan(output_parallel_dims)), instruction, may_combine_partial_sharding); } return changed; } bool InferScatterParallelShardingFromOperands( HloInstruction* instruction, const hlo_sharding_util::GatherScatterParallelDims& parallel_dims, bool may_combine_partial_sharding) { HloScatterInstruction* scatter = DynCast<HloScatterInstruction>(instruction); CHECK(scatter); const int64_t operand_count = scatter->scatter_operand_count(); auto scatter_operands = scatter->scatter_operands(); auto scatter_indices = scatter->scatter_indices(); auto scatter_updates = scatter->scatter_updates(); bool changed = false; auto aligned_operand_parallel_dims = hlo_sharding_util::IndexAlignedOperandParallelDims(parallel_dims); auto update_parallel_dims = hlo_sharding_util::GetScatterParallelUpdateDims( *instruction, parallel_dims); auto output_parallel_dims = aligned_operand_parallel_dims; // Infer output sharding from scatter operand sharding. Shape shape = operand_count == 1 ? instruction->shape() : ShapeUtil::GetSubshape(instruction->shape(), {0}); for (int64_t i = 0; i != operand_count; ++i) { if (hlo_sharding_util::IsSpatiallyPartitioned(scatter_operands[i])) { changed |= MaybeImproveInstructionSubSharding( hlo_sharding_util:: InferGatherScatterParallelShardingFromOperandSharding( scatter_operands[i]->sharding(), scatter_operands[i]->shape(), shape, absl::MakeConstSpan(aligned_operand_parallel_dims), absl::MakeConstSpan(output_parallel_dims)), instruction, {i}, may_combine_partial_sharding); } } // Infer output sharding from scatter indices sharding. if (hlo_sharding_util::IsSpatiallyPartitioned(scatter_indices)) { auto parallel_sharding_from_indices = hlo_sharding_util:: InferGatherScatterParallelShardingFromOperandSharding( scatter_indices->sharding(), scatter_indices->shape(), shape, absl::MakeConstSpan(parallel_dims.indices_parallel_dims), absl::MakeConstSpan(output_parallel_dims)); for (int64_t i = 0; i != operand_count; ++i) { changed |= MaybeImproveInstructionSubSharding( parallel_sharding_from_indices, instruction, {i}, may_combine_partial_sharding); } } // Infer output sharding from scatter update sharding. for (int64_t i = 0; i != operand_count; ++i) { if (hlo_sharding_util::IsSpatiallyPartitioned(scatter_updates[i])) { changed |= MaybeImproveInstructionSubSharding( hlo_sharding_util:: InferGatherScatterParallelShardingFromOperandSharding( scatter_updates[i]->sharding(), scatter_updates[i]->shape(), shape, absl::MakeConstSpan(update_parallel_dims), absl::MakeConstSpan(output_parallel_dims)), instruction, {i}, may_combine_partial_sharding); } } return changed; } bool CanPropagateThroughAtAggressiveLevel(const HloInstruction& inst, int64_t aggressiveness) { // At minimum aggressiveness, only allow pass-through ops. if (aggressiveness < 1 && !(inst.IsElementwise() || inst.IsCustomCall("Sharding")) && inst.opcode() != HloOpcode::kTranspose && inst.opcode() != HloOpcode::kReshape && inst.opcode() != HloOpcode::kTuple && inst.opcode() != HloOpcode::kGetTupleElement && inst.opcode() != HloOpcode::kWhile && inst.opcode() != HloOpcode::kDynamicSlice && inst.opcode() != HloOpcode::kDynamicUpdateSlice && inst.opcode() != HloOpcode::kOptimizationBarrier && inst.opcode() != HloOpcode::kConcatenate && inst.opcode() != HloOpcode::kCall && inst.opcode() != HloOpcode::kCopy) { return false; } // Broadcast propagation should have at least aggressiveness 2. if (aggressiveness < 2 && inst.opcode() == HloOpcode::kBroadcast) { return false; } return true; } bool SameShardingMetadata(const HloSharding& a, const HloSharding& b) { DCHECK_EQ(a, b); auto same_metadata = [](absl::Span<const OpMetadata> a, absl::Span<const OpMetadata> b) { if (a.size() != b.size()) return false; for (int i = 0, e = a.size(); i < e; ++i) { if (!protobuf_util::ProtobufEquals(a[i], b[i])) { return false; } } return true; }; if (a.IsTuple()) { for (int i = 0, e = a.tuple_elements().size(); i < e; ++i) { if (!same_metadata(a.tuple_elements()[i].metadata(), b.tuple_elements()[i].metadata())) { return false; } } return true; } else { return same_metadata(a.metadata(), b.metadata()); } } auto same_metadata = [](absl::Span<const OpMetadata> a, absl::Span<const OpMetadata> b) { if (a.size() != b.size()) return false; for (int i = 0, e = a.size(); i < e; ++i) { if (!protobuf_util::ProtobufEquals(a[i], b[i])) { return false; } } return true; }; bool AssignShardingMetadata( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { bool changed = false; for (HloComputation* computation : module->computations(execution_threads)) { for (HloInstruction* instruction : computation->instructions()) { const auto& metadata = instruction->metadata(); if (!instruction->has_sharding() || metadata.ByteSizeLong() == 0) { continue; } HloSharding sharding_with_metadata = instruction->sharding().WithMetadata({metadata}, /*overwrite=*/false); if (!SameShardingMetadata(instruction->sharding(), sharding_with_metadata)) { instruction->set_sharding(std::move(sharding_with_metadata)); changed = true; } } } return changed; } bool RemoveShardingMetadata( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { bool changed = false; for (HloComputation* computation : module->computations(execution_threads)) { for (HloInstruction* instruction : computation->instructions()) { if (!instruction->has_sharding()) { continue; } HloSharding sharding_no_metadata = instruction->sharding().WithoutMetadata(); if (!SameShardingMetadata(instruction->sharding(), sharding_no_metadata)) { instruction->set_sharding(std::move(sharding_no_metadata)); changed = true; } } } return changed; } absl::Status CheckAndUpdateDeviceAssignmentsInWhileBody( HloInstruction* while_instruction) { auto bad_status = [](HloInstruction* instruction, int64_t device, HloInstruction* channel_instruction, int64_t correct_device) { return FailedPrecondition( "Instruction: %s is on device: %d, which conflicts with device: %d " "of channel instruction: %s", instruction->name(), device, correct_device, channel_instruction->name()); }; CHECK_EQ(while_instruction->opcode(), HloOpcode::kWhile); HloComputation* while_body = while_instruction->while_body(); // Maps a device number to an instruction in the while_body with that // device assignment. std::map<int64_t, HloInstruction*> devices_to_instructions; std::optional<int64_t> unique_device = std::nullopt; HloInstruction* channel_instruction = nullptr; for (HloInstruction* instruction : while_body->instructions()) { if (instruction->sharding_unique_device()) { auto opcode = instruction->opcode(); int64_t device = *instruction->sharding_unique_device(); if (unique_device.has_value()) { if (*unique_device != device) { return bad_status(instruction, device, channel_instruction, *unique_device); } } else if (((opcode == HloOpcode::kSend || opcode == HloOpcode::kRecv) && !Cast<HloSendRecvInstruction>(instruction) ->is_host_transfer()) // Cross-replica AllReduces don't have a channel_id, and we // don't enforce any invariant about their device assignment. || ((opcode == HloOpcode::kAllReduce || opcode == HloOpcode::kReduceScatter) && instruction->channel_id())) { channel_instruction = instruction; unique_device = device; if (!devices_to_instructions.empty()) { for (auto it = devices_to_instructions.begin(); it != devices_to_instructions.end(); ++it) { if (*unique_device != it->first) { return bad_status(it->second, it->first, channel_instruction, *unique_device); } } } } else { devices_to_instructions[device] = instruction; } } } if (unique_device.has_value()) { auto while_device = while_instruction->sharding_unique_device(); if (while_device.has_value() && *unique_device != *while_device) { return bad_status(while_instruction, *while_device, channel_instruction, *unique_device); } auto body_root = while_body->root_instruction(); auto root_device = body_root->sharding_unique_device(); if (!root_device.has_value()) { body_root->set_device_sharding(*unique_device); } else if (*unique_device != *root_device) { return bad_status(body_root, *root_device, channel_instruction, *unique_device); } } return absl::OkStatus(); } auto bad_status = [](HloInstruction* instruction, int64_t device, HloInstruction* channel_instruction, int64_t correct_device) { return FailedPrecondition( "Instruction: %s is on device: %d, which conflicts with device: %d " "of channel instruction: %s", instruction->name(), device, correct_device, channel_instruction->name()); }; bool RefineManualAutoShardingFromAuto( const HloSharding& to_merge, absl::Span<const int64_t> unspecified_dims, HloSharding* auto_sharding, HloSharding* manual_sharding) { if (!manual_sharding->IsManualSubgroup() || auto_sharding->IsManualSubgroup() || !manual_sharding->HasPartialReplication() || manual_sharding->subgroup_types().size() != 2) { // We do not support nested subgroup manual. man_conversion_op must have // replication in order to be merged. return false; } HloSharding partial_rep = hlo_sharding_util::PartiallyReplicateTiledShardingOnAllDimsExcept( to_merge, unspecified_dims); if (partial_rep.IsTileMaximal()) { return false; } // Merge with the non-manual partial annotation. if (!hlo_sharding_util::MergeShardingIfCompatible( partial_rep, auto_sharding->NumTiles() + 1, auto_sharding)) { return false; } // Merge with the manual partial annotation. const int64_t data_rank = partial_rep.TiledDataRank(); // We are also merging the non-manual sharding into the manual sharding. To // leverage existing merging implementation, we treat the manual dim as a // data dim, and add it right before the replication dim. std::vector<int64_t> partial_manual_shape( partial_rep.tile_assignment().dimensions().begin(), partial_rep.tile_assignment().dimensions().end()); partial_manual_shape.insert(partial_manual_shape.begin() + data_rank, 1); auto partial_tiling_for_manual = partial_rep.tile_assignment().Reshape(partial_manual_shape); HloSharding partial_rep_for_manual = HloSharding::PartialTile( partial_tiling_for_manual, partial_rep.metadata()); auto man_tiling = manual_sharding->tile_assignment(); if (manual_sharding->subgroup_types().back() != OpSharding::REPLICATED) { // Move the manual dim before replication dim. std::vector<int> transposed_dims(man_tiling.num_dimensions()); absl::c_iota(transposed_dims, 0); std::swap(transposed_dims.back(), transposed_dims[data_rank]); man_tiling = man_tiling.Transpose(transposed_dims); } HloSharding tmp_sharding_for_merging = HloSharding::PartialTile( std::move(man_tiling), manual_sharding->metadata()); if (!hlo_sharding_util::MergeShardingIfCompatible( partial_rep_for_manual, tmp_sharding_for_merging.NumTiles() + 1, &tmp_sharding_for_merging)) { return false; } std::vector<OpSharding::Type> subgroup_types; subgroup_types.push_back(OpSharding::MANUAL); if (tmp_sharding_for_merging.HasPartialReplication()) { subgroup_types.push_back(OpSharding::REPLICATED); } *manual_sharding = HloSharding::Subgroup( tmp_sharding_for_merging.tile_assignment(), subgroup_types, tmp_sharding_for_merging.metadata()); return true; } bool RefineManualAutoShardingFromManual( const HloSharding& to_merge, absl::Span<const int64_t> unspecified_dims, HloSharding* auto_sharding, HloSharding* manual_sharding) { if (!to_merge.IsManualSubgroup() || !manual_sharding->IsManualSubgroup() || !manual_sharding->HasPartialReplication() || auto_sharding->IsManualSubgroup() || manual_sharding->subgroup_types().size() != 2) { return false; } HloSharding partial_rep = hlo_sharding_util::PartiallyReplicateTiledShardingOnAllDimsExcept( to_merge, unspecified_dims); if (partial_rep.IsTileMaximal()) { return false; } if (!hlo_sharding_util::MergeShardingIfCompatible( partial_rep, manual_sharding->NumTiles() + 1, manual_sharding)) { return false; } HloSharding partial_rep_for_auto = HloSharding::Subgroup( partial_rep.tile_assignment(), std::vector<OpSharding::Type>(partial_rep.subgroup_types().size(), OpSharding::REPLICATED), partial_rep.metadata()); if (!hlo_sharding_util::MergeShardingIfCompatible( partial_rep_for_auto, auto_sharding->NumTiles() + 1, auto_sharding)) { return false; } return true; } bool InferUnspecifiedDimsFromOperand(HloInstruction* annotate_op, absl::Span<const int64_t> unspecified_dims, HloInstruction** man_conversion_op_after) { // ProcessShardingInstruction will either keep the "Sharding" custom call as // is or replace it with a copy. CHECK(annotate_op->IsCustomCall("Sharding") || annotate_op->opcode() == HloOpcode::kCopy); if (!hlo_sharding_util::IsSpatiallyPartitioned(annotate_op->operand(0))) { return false; } const HloSharding& operand_sharding = annotate_op->operand(0)->sharding(); if (!operand_sharding.IsTiled()) { return false; } HloInstruction* man_conversion_op = nullptr; if (annotate_op->user_count() == 1) { HloInstruction* user = annotate_op->users()[0]; if (user->IsCustomCall("SPMDFullToShardShape") || user->IsCustomCall("SPMDShardToFullShape")) { std::vector<int64_t> user_unspec_dims; if (!sharding_op_util::ParseAttributes( Cast<HloCustomCallInstruction>(user)->opaque(), &user_unspec_dims) .ok()) { return false; } absl::c_sort(user_unspec_dims); if (unspecified_dims != user_unspec_dims) { // The manual/auto conversion op must have the same set of unspecified // dims. return false; } man_conversion_op = user; } } *man_conversion_op_after = man_conversion_op; if (man_conversion_op == nullptr) { HloSharding partial_replicated = hlo_sharding_util::PartiallyReplicateTiledShardingOnAllDimsExcept( operand_sharding, unspecified_dims); HloSharding sharding = annotate_op->sharding(); if (!hlo_sharding_util::MergeShardingIfCompatible( partial_replicated, sharding.NumTiles() + 1, &sharding)) { return false; } annotate_op->set_sharding(sharding); return true; } if (man_conversion_op->IsCustomCall("SPMDFullToShardShape")) { HloSharding auto_sharding = annotate_op->sharding(); HloSharding manual_sharding = man_conversion_op->sharding(); if (!RefineManualAutoShardingFromAuto(operand_sharding, unspecified_dims, &auto_sharding, &manual_sharding)) { return false; } annotate_op->set_sharding(auto_sharding); man_conversion_op->set_sharding(manual_sharding); return true; } CHECK(man_conversion_op->IsCustomCall("SPMDShardToFullShape")); HloSharding manual_sharding = annotate_op->sharding(); HloSharding auto_sharding = man_conversion_op->sharding(); if (!RefineManualAutoShardingFromManual(operand_sharding, unspecified_dims, &auto_sharding, &manual_sharding)) { return false; } annotate_op->set_sharding(manual_sharding); man_conversion_op->set_sharding(auto_sharding); return true; } bool InferUnspecifiedDimsFromOneUser(HloInstruction* annotate_op, const HloInstruction* user, int64_t aggressiveness, bool is_spmd, absl::Span<const int64_t> unspecified_dims, HloInstruction* man_conversion_op, const CallGraph& call_graph) { CHECK(annotate_op->IsCustomCall("Sharding") || annotate_op->opcode() == HloOpcode::kCopy); if (!user->has_sharding() || !user->sharding().IsTiled()) { return false; } std::optional<HloSharding> user_sharding = ShardingPropagation::GetShardingFromUser( man_conversion_op == nullptr ? *annotate_op : *man_conversion_op, *user, aggressiveness, is_spmd, call_graph, /*sharding_helper=*/nullptr); if (!user_sharding.has_value() || user_sharding->IsTileMaximal()) { return false; } if (man_conversion_op == nullptr) { HloSharding partial_replicated = hlo_sharding_util::PartiallyReplicateTiledShardingOnAllDimsExcept( *user_sharding, unspecified_dims); HloSharding sharding = annotate_op->sharding(); if (!hlo_sharding_util::MergeShardingIfCompatible( partial_replicated, sharding.NumTiles() + 1, &sharding)) { return false; } annotate_op->set_sharding(sharding); return true; } if (man_conversion_op->IsCustomCall("SPMDFullToShardShape")) { HloSharding auto_sharding = annotate_op->sharding(); HloSharding manual_sharding = man_conversion_op->sharding(); if (!RefineManualAutoShardingFromManual(*user_sharding, unspecified_dims, &auto_sharding, &manual_sharding)) { return false; } annotate_op->set_sharding(auto_sharding); man_conversion_op->set_sharding(manual_sharding); return true; } CHECK(man_conversion_op->IsCustomCall("SPMDShardToFullShape")); HloSharding manual_sharding = annotate_op->sharding(); HloSharding auto_sharding = man_conversion_op->sharding(); if (!RefineManualAutoShardingFromAuto(*user_sharding, unspecified_dims, &auto_sharding, &manual_sharding)) { return false; } annotate_op->set_sharding(manual_sharding); man_conversion_op->set_sharding(auto_sharding); return true; } bool InferUnspecifiedDimsFromUsers(HloInstruction* annotate_op, absl::Span<const int64_t> unspecified_dims, int64_t aggressiveness, bool is_spmd, HloInstruction** man_conversion_op_after, const CallGraph& call_graph) { HloInstruction* man_conversion_op = nullptr; if (annotate_op->user_count() == 1) { HloInstruction* user = annotate_op->users()[0]; if (user->IsCustomCall("SPMDFullToShardShape") || user->IsCustomCall("SPMDShardToFullShape")) { std::vector<int64_t> user_unspec_dims; absl::c_sort(user_unspec_dims); if (!sharding_op_util::ParseAttributes( Cast<HloCustomCallInstruction>(user)->opaque(), &user_unspec_dims) .ok() || unspecified_dims != user_unspec_dims) { // The manual/auto conversion op must have the same set of unspecified // dims. return false; } man_conversion_op = user; } } *man_conversion_op_after = man_conversion_op; HloInstruction* op_for_users = man_conversion_op == nullptr ? annotate_op : man_conversion_op; bool changed = false; for (HloInstruction* user : op_for_users->users()) { changed |= InferUnspecifiedDimsFromOneUser( annotate_op, user, aggressiveness, is_spmd, unspecified_dims, man_conversion_op, call_graph); } return changed; } bool InferUnspecifiedDimsFromShardGroup( HloInstruction* annotate_op, absl::Span<const int64_t> unspecified_dims, const absl::flat_hash_set<HloInstruction*>& shard_group) { // ProcessShardingInstruction will either keep the "Sharding" custom call as // is or replace it with a copy. CHECK(annotate_op->IsCustomCall("Sharding") || annotate_op->opcode() == HloOpcode::kCopy); // Do not propagate sharding to ShardBarrierTo custom-call. if (annotate_op->IsCustomCall(spmd::kShardBarrierTo)) { return false; } bool changed = false; for (const HloInstruction* member : shard_group) { if (member == annotate_op) { continue; } // Do not propagate sharding from ShardBarrierFrom custom-call. if (member->IsCustomCall(spmd::kShardBarrierFrom)) { continue; } if (!hlo_sharding_util::IsSpatiallyPartitioned(member)) { continue; } const HloSharding& member_sharding = member->sharding(); if (!member_sharding.IsTiled()) { continue; } HloSharding partial_replicated = hlo_sharding_util::PartiallyReplicateTiledShardingOnAllDimsExcept( member_sharding, unspecified_dims); HloSharding sharding = annotate_op->sharding(); if (!hlo_sharding_util::MergeShardingIfCompatible( partial_replicated, sharding.NumTiles() + 1, &sharding)) { continue; } annotate_op->set_sharding(sharding); changed |= true; } return changed; } bool IsCSEPreventionTarget(const HloInstruction* instruction) { // Scalar broadcasts are the most common CSE target that causes cross-layer // propagation on unrelated subgraphs. return instruction->opcode() == HloOpcode::kBroadcast && instruction->operand(0)->shape().rank() == 0; } HloSharding SetCSEPreventionSharding(const HloSharding& sharding) { OpMetadata metadata; metadata.set_op_name("_sharding_propagation_cse_prevention"); return sharding.WithMetadata({metadata}, /*overwrite=*/true); } bool IsCSEPreventionSharding(const HloSharding& sharding) { if (sharding.metadata().size() != 1) { return false; } return sharding.metadata()[0].op_name() == "_sharding_propagation_cse_prevention"; } bool InferDotShardingFromOperands( HloInstruction* instruction, const CallGraph& call_graph, const dot_as_convolution_util::DotConvolutionDimsInfo& dnums, bool may_combine_partial_sharding, bool is_spmd) { auto from_operand = [&](int64_t operand_index) { auto operand = instruction->operand(operand_index); const HloSharding& operand_sharding = operand->sharding(); if (operand_sharding.IsTileMaximal()) { return operand_sharding; } std::vector<int64_t> contracting_dims; contracting_dims.reserve(dnums.contracting_dims.size()); for (const auto& dim : dnums.contracting_dims) { contracting_dims.push_back(operand_index == 0 ? dim.lhs : dim.rhs); } // It's possible that some size-1 spatial dims of convolutions are parsed as // non-contracting dims. We might have tiled dimensions on them. for (const auto& dim : operand_index == 0 ? dnums.rhs_non_contracting_dims : dnums.lhs_non_contracting_dims) { int64_t d = operand_index == 0 ? dim.lhs : dim.rhs; if (d >= 0) { contracting_dims.push_back(d); } } auto replicate_contracting_dims = hlo_sharding_util::PartiallyReplicateTiledShardingOnDims( operand_sharding, contracting_dims); std::vector<int64_t> out_dims_to_op_perm(instruction->shape().rank(), -1); std::vector<int64_t> op_dims_to_output_perm(operand->shape().rank(), -1); for (const auto& dim : dnums.batch_dims) { out_dims_to_op_perm[dim.output] = operand_index == 0 ? dim.lhs : dim.rhs; op_dims_to_output_perm[operand_index == 0 ? dim.lhs : dim.rhs] = dim.output; } for (const auto& dim : operand_index == 0 ? dnums.lhs_non_contracting_dims : dnums.rhs_non_contracting_dims) { out_dims_to_op_perm[dim.output] = operand_index == 0 ? dim.lhs : dim.rhs; op_dims_to_output_perm[operand_index == 0 ? dim.lhs : dim.rhs] = dim.output; } return *hlo_sharding_util::TransposeShardingWithCollapsedDims( replicate_contracting_dims, op_dims_to_output_perm, out_dims_to_op_perm); }; std::optional<HloSharding> improved_operand_0; std::optional<HloSharding> improved_operand_1; if (hlo_sharding_util::IsSpatiallyPartitioned(instruction->operand(0))) { improved_operand_0 = ReturnImprovedSharding( from_operand(0), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/false); } if (hlo_sharding_util::IsSpatiallyPartitioned(instruction->operand(1))) { improved_operand_1 = ReturnImprovedSharding( from_operand(1), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/false); } // If not improved sharding found then do not set any sharding. if (!improved_operand_0.has_value() && !improved_operand_1.has_value()) { return false; } // Sharding found from operand 0 but not operand 1. Set sharding from operand // 0 if (improved_operand_0.has_value() && !improved_operand_1.has_value()) { instruction->set_sharding(*improved_operand_0); return true; } // Sharding found from operand 1 but not operand 0. Set sharding from operand // 1 if (!improved_operand_0.has_value() && improved_operand_1.has_value()) { instruction->set_sharding(*improved_operand_1); return true; } CHECK(improved_operand_0.has_value() && improved_operand_1.has_value()); std::optional<HloSharding> lookahead_sharding = LookaheadUserSharding(instruction, is_spmd, call_graph); std::array<HloSharding, 2> sharding_priority = {*improved_operand_0, *improved_operand_1}; bool priority_defined_with_lookahead = false; // Found sharding from lookahead. if (lookahead_sharding.has_value()) { const bool operand_0_is_lookahead_subtiling = hlo_sharding_util::IsSubTilingOrEqualSharding( instruction->shape(), *lookahead_sharding, *improved_operand_0); const bool operand_1_is_lookahead_subtiling = hlo_sharding_util::IsSubTilingOrEqualSharding( instruction->shape(), *lookahead_sharding, *improved_operand_1); // If the sharding from operand 0 is a subtiling of the user, but not the // one from operand 1 prioritize that sharding. if (operand_0_is_lookahead_subtiling && !operand_1_is_lookahead_subtiling) { priority_defined_with_lookahead = true; } // If the sharding from operand 1 is a subtiling of the user, but not the // one from operand 0 prioritize that sharding. if (!operand_0_is_lookahead_subtiling && operand_1_is_lookahead_subtiling) { instruction->set_sharding(*improved_operand_1); std::swap(sharding_priority[0], sharding_priority[1]); priority_defined_with_lookahead = true; } } // If lookahead didn't define a priority then use size. if (!priority_defined_with_lookahead && ShapeUtil::ByteSizeOf(instruction->operand(0)->shape()) < ShapeUtil::ByteSizeOf(instruction->operand(1)->shape())) { std::swap(sharding_priority[0], sharding_priority[1]); } // Set primary sharding to the instruction and then try to improve it with // the secondary sharding. instruction->set_sharding(sharding_priority[0]); MaybeImproveInstructionSharding(sharding_priority[1], instruction, may_combine_partial_sharding); return true; } auto from_operand = [&](int64_t operand_index) { auto operand = instruction->operand(operand_index); const HloSharding& operand_sharding = operand->sharding(); if (operand_sharding.IsTileMaximal()) { return operand_sharding; } std::vector<int64_t> contracting_dims; contracting_dims.reserve(dnums.contracting_dims.size()); for (const auto& dim : dnums.contracting_dims) { contracting_dims.push_back(operand_index == 0 ? dim.lhs : dim.rhs); } // It's possible that some size-1 spatial dims of convolutions are parsed as // non-contracting dims. We might have tiled dimensions on them. for (const auto& dim : operand_index == 0 ? dnums.rhs_non_contracting_dims : dnums.lhs_non_contracting_dims) { int64_t d = operand_index == 0 ? dim.lhs : dim.rhs; if (d >= 0) { contracting_dims.push_back(d); } } auto replicate_contracting_dims = hlo_sharding_util::PartiallyReplicateTiledShardingOnDims( operand_sharding, contracting_dims); std::vector<int64_t> out_dims_to_op_perm(instruction->shape().rank(), -1); std::vector<int64_t> op_dims_to_output_perm(operand->shape().rank(), -1); for (const auto& dim : dnums.batch_dims) { out_dims_to_op_perm[dim.output] = operand_index == 0 ? dim.lhs : dim.rhs; op_dims_to_output_perm[operand_index == 0 ? dim.lhs : dim.rhs] = dim.output; } for (const auto& dim : operand_index == 0 ? dnums.lhs_non_contracting_dims : dnums.rhs_non_contracting_dims) { out_dims_to_op_perm[dim.output] = operand_index == 0 ? dim.lhs : dim.rhs; op_dims_to_output_perm[operand_index == 0 ? dim.lhs : dim.rhs] = dim.output; } return *hlo_sharding_util::TransposeShardingWithCollapsedDims( replicate_contracting_dims, op_dims_to_output_perm, out_dims_to_op_perm); }; bool InferConvolutionShardingFromOperands(HloInstruction* instruction, const CallGraph& call_graph, int64_t aggressiveness, bool may_combine_partial_sharding, bool is_spmd) { auto get_partitions_for_dims = [&](const HloInstruction* inst, absl::Span< const dot_as_convolution_util::DotConvolutionDimsInfo::DimNums> dims, int lhs_or_rhs) { int64_t partitions = 1; if (!inst->has_sharding()) { return partitions; } const auto& sharding = inst->sharding(); if (sharding.IsTileMaximal()) { return partitions; } for (const auto& dim : dims) { if (lhs_or_rhs == 0) { partitions *= sharding.tile_assignment().dim(dim.lhs); } else { CHECK_EQ(lhs_or_rhs, 1); partitions *= sharding.tile_assignment().dim(dim.rhs); } } return partitions; }; auto dot_dims = dot_as_convolution_util::ParseConvolutionDimsInfo(instruction); const int64_t lhs_conv_spatial_partitions = get_partitions_for_dims( instruction->operand(0), dot_dims.conv_spatial_dims, 0); const int64_t rhs_conv_spatial_partitions = get_partitions_for_dims( instruction->operand(1), dot_dims.conv_spatial_dims, 1); if (dot_dims.conv_spatial_dims.empty() || (lhs_conv_spatial_partitions == 1 && rhs_conv_spatial_partitions == 1 && instruction->batch_group_count() == 1 && instruction->feature_group_count() == 1)) { return InferDotShardingFromOperands(instruction, call_graph, dot_dims, may_combine_partial_sharding, is_spmd); } const auto& dnums = instruction->convolution_dimension_numbers(); const HloInstruction* lhs = instruction->operand(0); auto get_tiled_sharding_based_on_lhs = [&] { CHECK(!lhs->sharding().IsTileMaximal()); std::vector<int64_t> output_to_lhs_indices(instruction->shape().rank()); output_to_lhs_indices[dnums.output_batch_dimension()] = dnums.input_batch_dimension(); output_to_lhs_indices[dnums.output_feature_dimension()] = dnums.input_feature_dimension(); for (int64_t i = 0; i < dnums.input_spatial_dimensions_size(); ++i) { output_to_lhs_indices[dnums.output_spatial_dimensions(i)] = dnums.input_spatial_dimensions(i); } return hlo_sharding_util::TransposeSharding(lhs->sharding(), output_to_lhs_indices); }; if (!hlo_sharding_util::IsSpatiallyPartitioned(lhs)) { return false; } if (lhs->sharding().IsTileMaximal()) { return MaybeImproveInstructionSharding(lhs->sharding(), instruction, may_combine_partial_sharding); } if (IsConvolutionKernelSmall(instruction)) { // If the kernel is small compared to the input then we can generate an // output what is sharded the same way as the input. const auto& tile_assignment = lhs->sharding().tile_assignment(); if (tile_assignment.dim(dnums.input_feature_dimension()) > 1) { return false; } return MaybeImproveInstructionSharding(get_tiled_sharding_based_on_lhs(), instruction, may_combine_partial_sharding); } // If the kernel is large (e.g., backward convolution) then we only support // replicated output. We intend to keep the sharding along the batch dimension // between lhs and output. return MaybeImproveInstructionSharding( hlo_sharding_util::PartiallyReplicateTiledShardingOnAllDimsExcept( lhs->sharding(), {dnums.input_batch_dimension()}), instruction, may_combine_partial_sharding); } [&](const HloInstruction* inst, absl::Span< const dot_as_convolution_util::DotConvolutionDimsInfo::DimNums> dims, int lhs_or_rhs) { int64_t partitions = 1; if (!inst->has_sharding()) { return partitions; } const auto& sharding = inst->sharding(); if (sharding.IsTileMaximal()) { return partitions; } for (const auto& dim : dims) { if (lhs_or_rhs == 0) { partitions *= sharding.tile_assignment().dim(dim.lhs); } else { CHECK_EQ(lhs_or_rhs, 1); partitions *= sharding.tile_assignment().dim(dim.rhs); } } return partitions; }; auto get_tiled_sharding_based_on_lhs = [&] { CHECK(!lhs->sharding().IsTileMaximal()); std::vector<int64_t> output_to_lhs_indices(instruction->shape().rank()); output_to_lhs_indices[dnums.output_batch_dimension()] = dnums.input_batch_dimension(); output_to_lhs_indices[dnums.output_feature_dimension()] = dnums.input_feature_dimension(); for (int64_t i = 0; i < dnums.input_spatial_dimensions_size(); ++i) { output_to_lhs_indices[dnums.output_spatial_dimensions(i)] = dnums.input_spatial_dimensions(i); } return hlo_sharding_util::TransposeSharding(lhs->sharding(), output_to_lhs_indices); }; std::optional<HloSharding> InferBroadcastOperandSharding( const HloInstruction& instruction, bool is_spmd) { if (instruction.sharding().IsReplicated() || instruction.sharding().IsManual()) { return instruction.sharding(); } std::vector<int64_t> dims_to_replicate; bool needs_replication = false; for (int64_t i = 0; i < instruction.shape().rank(); ++i) { if (absl::c_count(instruction.dimensions(), i) == 0) { dims_to_replicate.push_back(i); if (instruction.sharding().tile_assignment().dim(i) > 1) { needs_replication = true; } } } // If not SPMD, only support when none of the partitioned dimensions in // the broadcast output belong to new dimensions. if (!is_spmd && needs_replication) { return std::nullopt; } return hlo_sharding_util::RemoveShapeDimensions( hlo_sharding_util::PartiallyReplicateTiledShardingOnDims( instruction.sharding(), dims_to_replicate), dims_to_replicate); } bool InferReduceShardingFromOperand(HloInstruction* instruction, bool may_combine_partial_sharding, bool is_spmd) { auto get_maybe_tuple_sharding = [&](HloSharding sharding) { if (instruction->shape().IsArray()) { return sharding; } std::vector<HloSharding> tuple(instruction->shape().tuple_shapes_size(), std::move(sharding)); return HloSharding::Tuple(instruction->shape(), tuple); }; auto* reduce = Cast<HloReduceInstruction>(instruction); bool changed = false; for (HloInstruction* operand : reduce->inputs()) { if (!hlo_sharding_util::IsSpatiallyPartitioned(operand)) { continue; } if (operand->sharding().IsReplicated() || (!is_spmd && absl::c_any_of(instruction->dimensions(), [operand](int64_t dim) { return operand->sharding().tile_assignment().dim(dim) > 1; }))) { // We are reducing along one of the sharded dimensions. We only // support this in SPMD. changed |= MaybeImproveInstructionSharding( get_maybe_tuple_sharding( hlo_sharding_util::ReplicateAllDataDims(operand->sharding())), reduce, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); continue; } auto after_partial_replication = operand->sharding().IsReplicated() ? operand->sharding() : hlo_sharding_util::PartiallyReplicateTiledShardingOnDims( operand->sharding(), reduce->dimensions()); if (after_partial_replication.IsReplicated()) { changed |= MaybeImproveInstructionSharding( get_maybe_tuple_sharding(after_partial_replication), reduce, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); continue; } // Use the same sharding for all tuple elements, because they are part // of the same reduce instruction. HloSharding new_sharding = get_maybe_tuple_sharding(hlo_sharding_util::RemoveShapeDimensions( after_partial_replication, reduce->dimensions())); changed |= MaybeImproveInstructionSharding( std::move(new_sharding), reduce, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(reduce) == 1); } return changed; } auto get_maybe_tuple_sharding = [&](HloSharding sharding) { if (instruction->shape().IsArray()) { return sharding; } std::vector<HloSharding> tuple(instruction->shape().tuple_shapes_size(), std::move(sharding)); return HloSharding::Tuple(instruction->shape(), tuple); }; absl::c_any_of(instruction->dimensions(), [operand](int64_t dim) { return operand->sharding().tile_assignment().dim(dim) > 1; }))) { absl::StatusOr<bool> ProcessShardingInstruction( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads, bool replace_sharding_with_copy, absl::flat_hash_map<const HloInstruction*, std::vector<int64_t>>* unspecified_dims, std::vector<HloSharding>* saved_root_shardings, absl::flat_hash_map<int64_t, HloSharding>* saved_parameter_shardings, absl::flat_hash_map<HloInstruction*, int64_t>* instruction_to_shard_group_id, absl::flat_hash_map<int64_t, absl::flat_hash_set<HloInstruction*>>* shard_group_id_to_shard_as_group, absl::flat_hash_map<int64_t, absl::flat_hash_set<HloInstruction*>>* shard_group_id_to_shard_like_group, const std::vector<bool>* allow_spmd_sharding_propagation_to_parameters_vector) { bool changed = false; const bool use_shard_group = instruction_to_shard_group_id && shard_group_id_to_shard_as_group && shard_group_id_to_shard_like_group; // Process shard group instruction and returns if current instruction needs // to be removed. auto process_shard_group_instruction = [&](HloInstruction* instruction, bool replaced_with_copy) -> absl::StatusOr<bool> { // Run shard group processing IFF it's not CSE prevention. if (replace_sharding_with_copy) { if (use_shard_group && instruction->has_sharding() && instruction->sharding().IsShardGroup()) { if (instruction->IsCustomCall("Sharding")) { CHECK(instruction->operand(0)->opcode() != HloOpcode::kParameter || (allow_spmd_sharding_propagation_to_parameters_vector && allow_spmd_sharding_propagation_to_parameters_vector->size() == module->entry_computation()->num_parameters() && allow_spmd_sharding_propagation_to_parameters_vector->at( instruction->operand(0)->parameter_number()))); } if (instruction->IsCustomCall("Sharding") && !replaced_with_copy) { // Pass shard group to operand sharding custom-call if it's not // replaced with a copy, meaning that the shardings are to annotate // shard_group. HloSharding operand_sharding = instruction->operand(0)->has_sharding() ? instruction->operand(0)->sharding() : HloSharding::Unknown(); operand_sharding.SetShardGroup( instruction->sharding().GetShardGroup()); instruction->mutable_operand(0)->set_sharding( std::move(operand_sharding)); return true; } else { // Otherwise store the shard group relations. const int64_t shard_group_id = instruction->sharding().GetShardGroup().shard_group_id; (*instruction_to_shard_group_id)[instruction] = shard_group_id; if (instruction->sharding().IsShardAs()) { auto& shard_as_group = (*shard_group_id_to_shard_as_group)[shard_group_id]; if (!shard_as_group.empty()) { CHECK(ShapeUtil::SameDimensions( instruction->shape(), (*shard_as_group.begin())->shape())) << "Instruction: " << instruction->ToString() << " has different shape from the shapes of the other " "instructions within the same shard_as group: " << (*shard_as_group.begin())->shape().ToString(); } shard_as_group.insert(instruction); } else { auto& shard_like_group = (*shard_group_id_to_shard_like_group)[shard_group_id]; if (!shard_like_group.empty()) { CHECK(ShapeUtil::SameDimensions( instruction->shape(), (*shard_like_group.begin())->shape())) << "Instruction: " << instruction->ToString() << " has different shape from the shapes of the other " "instructions within the same shard_like group: " << (*shard_like_group.begin())->shape().ToString(); } shard_like_group.insert(instruction); } HloSharding sharding = instruction->sharding(); sharding.ClearShardGroup(); instruction->set_sharding(std::move(sharding)); } } } return false; }; for (HloComputation* computation : module->computations(execution_threads)) { auto instructions = computation->MakeInstructionPostOrder(); for (auto it = instructions.rbegin(); it != instructions.rend(); ++it) { HloInstruction* instruction = *it; if (instruction->IsCustomCall("Sharding")) { HloSharding original_sharding = instruction->sharding(); TF_RET_CHECK(instruction->has_sharding()) << "Sharding instruction must have a sharding attribute"; VLOG(3) << "ProcessShardingInstruction: " << instruction->ToString(); std::vector<int64_t> unspec_dims; TF_RETURN_IF_ERROR(sharding_op_util::ParseAttributes( Cast<HloCustomCallInstruction>(instruction)->opaque(), &unspec_dims)); bool replaced_with_copy = replace_sharding_with_copy && (!original_sharding.IsUnknown() || instruction->operand(0)->opcode() == HloOpcode::kParameter); // Replace the sharding instruction with a copy node so that it does not // need special handling. if (replaced_with_copy) { auto copy = computation->AddInstruction(HloInstruction::CreateUnary( instruction->shape(), HloOpcode::kCopy, instruction->mutable_operand(0))); TF_ASSIGN_OR_RETURN( std::ignore, computation->ReplaceInstruction( instruction, copy, /*preserve_sharding=*/false, /*relay_control_dependency=*/false, /*remove_unused_operands=*/false)); copy->set_sharding(std::move(original_sharding)); instruction = copy; changed = true; } TF_ASSIGN_OR_RETURN( bool shard_group_remove_instruction, process_shard_group_instruction(instruction, replaced_with_copy)); if (!unspec_dims.empty()) { absl::c_sort(unspec_dims); unspecified_dims->emplace(instruction, std::move(unspec_dims)); } else if (!instruction->operand(0)->has_sharding()) { instruction->mutable_operand(0)->set_sharding( instruction->sharding()); } if (shard_group_remove_instruction) { TF_ASSIGN_OR_RETURN(std::ignore, computation->ReplaceInstruction( instruction, instruction->mutable_operand(0), /*preserve_sharding=*/false, /*relay_control_dependency=*/false, /*remove_unused_operands=*/false)); } } else { TF_ASSIGN_OR_RETURN(std::ignore, process_shard_group_instruction( instruction, /*replaced_with_copy=*/false)); } } } // Save the original shardings of parameters/outputs. HloInstruction* root_instr = module->entry_computation()->root_instruction(); if (saved_root_shardings != nullptr && root_instr->shape().IsTuple() && root_instr->has_sharding()) { saved_root_shardings->reserve( root_instr->sharding().tuple_elements().size()); for (const HloSharding& sharding : root_instr->sharding().tuple_elements()) { saved_root_shardings->push_back(sharding); } } if (saved_parameter_shardings != nullptr) { auto params = module->entry_computation()->parameter_instructions(); for (int64_t i = 0; i < params.size(); ++i) { if (params[i]->has_sharding()) { saved_parameter_shardings->insert({i, params[i]->sharding()}); } } } return changed; } [&](HloInstruction* instruction, bool replaced_with_copy) -> absl::StatusOr<bool> { // Run shard group processing IFF it's not CSE prevention. if (replace_sharding_with_copy) { if (use_shard_group && instruction->has_sharding() && instruction->sharding().IsShardGroup()) { if (instruction->IsCustomCall("Sharding")) { CHECK(instruction->operand(0)->opcode() != HloOpcode::kParameter || (allow_spmd_sharding_propagation_to_parameters_vector && allow_spmd_sharding_propagation_to_parameters_vector->size() == module->entry_computation()->num_parameters() && allow_spmd_sharding_propagation_to_parameters_vector->at( instruction->operand(0)->parameter_number()))); } if (instruction->IsCustomCall("Sharding") && !replaced_with_copy) { // Pass shard group to operand sharding custom-call if it's not // replaced with a copy, meaning that the shardings are to annotate // shard_group. HloSharding operand_sharding = instruction->operand(0)->has_sharding() ? instruction->operand(0)->sharding() : HloSharding::Unknown(); operand_sharding.SetShardGroup( instruction->sharding().GetShardGroup()); instruction->mutable_operand(0)->set_sharding( std::move(operand_sharding)); return true; } else { // Otherwise store the shard group relations. const int64_t shard_group_id = instruction->sharding().GetShardGroup().shard_group_id; (*instruction_to_shard_group_id)[instruction] = shard_group_id; if (instruction->sharding().IsShardAs()) { auto& shard_as_group = (*shard_group_id_to_shard_as_group)[shard_group_id]; if (!shard_as_group.empty()) { CHECK(ShapeUtil::SameDimensions( instruction->shape(), (*shard_as_group.begin())->shape())) << "Instruction: " << instruction->ToString() << " has different shape from the shapes of the other " "instructions within the same shard_as group: " << (*shard_as_group.begin())->shape().ToString(); } shard_as_group.insert(instruction); } else { auto& shard_like_group = (*shard_group_id_to_shard_like_group)[shard_group_id]; if (!shard_like_group.empty()) { CHECK(ShapeUtil::SameDimensions( instruction->shape(), (*shard_like_group.begin())->shape())) << "Instruction: " << instruction->ToString() << " has different shape from the shapes of the other " "instructions within the same shard_like group: " << (*shard_like_group.begin())->shape().ToString(); } shard_like_group.insert(instruction); } HloSharding sharding = instruction->sharding(); sharding.ClearShardGroup(); instruction->set_sharding(std::move(sharding)); } } } return false; }; VLOG(3) << "ProcessShardingInstruction: " << instruction->ToString(); int64_t ComputeNonRootUsers(const HloInstruction* instr) { int64_t non_root_users = instr->users().size(); for (int i = 0; i < instr->users().size(); ++i) { if (instr->users()[i] == instr->parent()->root_instruction()) { --non_root_users; } } return non_root_users; } /*static*/ absl::Status ShardingPropagation::NormalizeDomain( const DomainMetadata::Domain& domain, const DomainMetadata* metadata) { if (metadata != nullptr) { TF_ASSIGN_OR_RETURN(const auto& sharding_metadata, ShardingMetadata::ToShardingMetadata(metadata)); const auto& sharding = sharding_metadata->sharding(); if (sharding != nullptr) { bool is_spatially_partitioned = !sharding->HasUniqueDevice(); if (sharding->IsTuple()) { is_spatially_partitioned = absl::c_any_of( sharding->tuple_elements(), [](const HloSharding& s) { return !s.HasUniqueDevice(); }); } if (is_spatially_partitioned) { for (HloInstruction* d : domain.exit_domains) { HloInstruction* operand = d->mutable_operand(0); // Set sharding only if it is different. We don't overwrite the // metadata if it has the same sharding besides metadata. if (!operand->has_sharding() || operand->sharding() != *sharding) { HloSharding operand_sharding = *sharding; if (operand->shape().IsTuple() && !sharding->IsTuple()) { // Expand sharding into tuple sharding per // CloneShardingForDomain() in // third_party/tensorflow/compiler/xla/hlo/ir/hlo_sharding_metadata.cc operand_sharding = HloSharding::SingleTuple(operand->shape(), *sharding); } operand->set_sharding(std::move(operand_sharding)); } } return absl::OkStatus(); } } } return ShardingMetadata::NormalizeShardingDomain(domain, metadata); } std::optional<HloSharding> ShardingPropagation::GetShardingFromUser( const HloInstruction& instruction, const HloInstruction& user, int64_t aggressiveness, bool is_spmd, const CallGraph& call_graph, const CustomCallShardingHelper* sharding_helper) { if (!CanPropagateThroughAtAggressiveLevel(user, aggressiveness)) { return std::nullopt; } if (!hlo_sharding_util::IsSpatiallyPartitioned(&user)) { return std::nullopt; } const bool may_combine_partial_sharding = is_spmd && aggressiveness > 0; switch (user.opcode()) { case HloOpcode::kBroadcast: { return InferBroadcastOperandSharding(user, is_spmd); } case HloOpcode::kConcatenate: { if (aggressiveness == 0) { return std::nullopt; } if (user.sharding().IsReplicated()) { return user.sharding(); } const int64_t cdim = user.concatenate_dimension(); auto& tile_assignment = user.sharding().tile_assignment(); if (tile_assignment.dim(cdim) == 1) { // If we are concatenating along a non-sharded dimension then the // operands should have the same sharding as the result. return user.sharding(); } if (is_spmd) { // SPMD doesn't support tiling with part of the devices. Return the same // sharding. return user.sharding(); } // If we are concatenating along a sharded dimension then we want the // operands to be distributed among the devices their data is used. int64_t start_offset = 0; for (HloInstruction* op : user.operands()) { if (op == &instruction) { break; } start_offset += op->shape().dimensions(cdim); } const int64_t tile_shape = CeilOfRatio( user.shape().dimensions(cdim), tile_assignment.dimensions()[cdim]); std::vector<int64_t> start_indices(tile_assignment.num_dimensions()); std::vector<int64_t> end_indices(tile_assignment.dimensions().begin(), tile_assignment.dimensions().end()); start_indices[cdim] = start_offset / tile_shape; end_indices[cdim] = CeilOfRatio( start_offset + instruction.shape().dimensions(cdim), tile_shape); auto new_tile_assignment = tile_assignment.array().Slice(start_indices, end_indices); if (new_tile_assignment.num_elements() == 1) { return HloSharding::AssignDevice(*new_tile_assignment.begin(), user.sharding().metadata()); } return HloSharding::Tile(std::move(new_tile_assignment), user.sharding().metadata()); } case HloOpcode::kConvolution: { auto dot_dims = dot_as_convolution_util::ParseConvolutionDimsInfo(&user); if (dot_dims.conv_spatial_dims.empty()) { int64_t op_idx = user.operand_index(&instruction); return hlo_sharding_util::InferDotOperandSharding( &user, op_idx, dot_dims, /*consider_other_operand=*/true, may_combine_partial_sharding); } return std::nullopt; } case HloOpcode::kDynamicSlice: case HloOpcode::kDynamicUpdateSlice: { if (aggressiveness == 0) { return std::nullopt; } if (user.sharding().IsReplicated()) { return user.sharding(); } if (user.opcode() == HloOpcode::kDynamicUpdateSlice && &instruction == user.operand(0)) { return user.sharding(); } const HloInstruction* operand = user.opcode() == HloOpcode::kDynamicSlice ? user.operand(0) : user.operand(1); if (&instruction != operand) { return std::nullopt; } if (is_spmd) { return user.sharding(); } const auto& tile_assignment = user.sharding().tile_assignment(); for (int64_t i = 0; i < user.shape().rank(); ++i) { if (tile_assignment.dim(i) > 1 && user.shape().dimensions(i) != operand->shape().dimensions(i)) { return std::nullopt; } } return user.sharding(); } case HloOpcode::kReduceWindow: { auto* reduce_window = Cast<HloReduceWindowInstruction>(&user); if (!absl::c_linear_search(reduce_window->inputs(), &instruction)) { return std::nullopt; } if (reduce_window->shape().IsTuple()) { auto sub_sharding = reduce_window->sharding().GetSubSharding( reduce_window->shape(), {reduce_window->operand_index(&instruction)}); return sub_sharding; } return reduce_window->sharding(); } case HloOpcode::kReshape: { return hlo_sharding_util::PropagateShardingThroughReshape( user.shape(), instruction.shape(), user.sharding()); } case HloOpcode::kPad: { if (&instruction != user.operand(0)) { return std::nullopt; } return user.sharding(); } case HloOpcode::kSlice: { return user.sharding(); } case HloOpcode::kTranspose: { // Calculate the dimension numbers for reversing the current transpose // and then use TransposeSharding to convert the output sharding to an // input sharding. std::vector<int64_t> reverse_dimensions(user.dimensions().size()); for (int64_t i = 0; i < user.dimensions().size(); ++i) { reverse_dimensions[user.dimensions(i)] = i; } return hlo_sharding_util::TransposeSharding(user.sharding(), reverse_dimensions); } case HloOpcode::kTuple: { auto sub_sharding = user.sharding().GetSubSharding( user.shape(), {user.operand_index(&instruction)}); // In case the instruction is used as the operands multiple times within // this tuple, we will return the most specific sharding and propagate up. for (int64_t i = 0; i < user.shape().tuple_shapes_size(); ++i) { if (user.operand(i) == &instruction) { // Only evaluate GetSubSharding if this operand is of interest, // as it is relatively expensive. HloSharding alternative_sub_sharding = user.sharding().GetSubSharding(user.shape(), {i}); if (hlo_sharding_util::IsShardingMoreSpecific( alternative_sub_sharding, sub_sharding)) { sub_sharding = alternative_sub_sharding; } } } return sub_sharding; } case HloOpcode::kGetTupleElement: { int64_t sharding_index = 0; for (int i = 0; i < instruction.shape().tuple_shapes_size(); ++i) { if (i == user.tuple_index()) { break; } if (instruction.shape().tuple_shapes(i).IsArray()) { sharding_index += 1; } else { sharding_index += ShapeUtil::GetLeafCount(instruction.shape().tuple_shapes(i)); } } if (user.shape().IsArray()) { // Use ReplicateAllDataDims instead of HloSharding::Replicate() to // preserve manual subgroups. HloSharding new_sharding = instruction.has_sharding() ? instruction.sharding() : HloSharding::SingleTuple( instruction.shape(), hlo_sharding_util::ReplicateAllDataDims(user.sharding())); new_sharding.tuple_elements()[sharding_index] = user.sharding(); return new_sharding; } else { if (user.sharding().tuple_elements().empty()) { return std::nullopt; } HloSharding new_sharding = instruction.has_sharding() ? instruction.sharding() : HloSharding::SingleTuple( instruction.shape(), hlo_sharding_util::ReplicateAllDataDims( user.sharding().tuple_elements()[0])); for (int64_t i = 0; i < user.sharding().tuple_elements().size(); ++i) { new_sharding.tuple_elements()[sharding_index + i] = user.sharding().tuple_elements()[i]; } return new_sharding; } } case HloOpcode::kDot: { int64_t op_idx = user.operand_index(&instruction); auto dnums = dot_as_convolution_util::ParseDotGeneralFromDot(&user); return hlo_sharding_util::InferDotOperandSharding( &user, op_idx, dnums, /*consider_other_operand=*/true, may_combine_partial_sharding); } case HloOpcode::kReduce: { if (instruction.shape().rank() == 0) { return std::nullopt; } auto user_sharding = user.shape().IsTuple() ? user.sharding().GetSubSharding( user.shape(), {user.operand_index(&instruction)}) : user.sharding(); if (!user_sharding.IsTileMaximal()) { std::vector<int64_t> target_tile_assignment_dimensions( instruction.shape().rank() + (user_sharding.ReplicateOnLastTileDim() ? 1 : 0) + user_sharding.subgroup_types().size()); const auto& dimensions = user.dimensions(); int64_t next_output_dim = 0; for (int64_t i = 0; i < target_tile_assignment_dimensions.size(); ++i) { if (absl::c_find(dimensions, i) == dimensions.end()) { target_tile_assignment_dimensions[i] = user_sharding.tile_assignment().dim(next_output_dim++); } else { target_tile_assignment_dimensions[i] = 1; } } auto tile_assignment = user_sharding.tile_assignment().Reshape( target_tile_assignment_dimensions); user_sharding = user_sharding.ReplicateOnLastTileDim() ? HloSharding::PartialTile(tile_assignment, user_sharding.metadata()) : HloSharding::Subgroup(tile_assignment, user_sharding.subgroup_types(), user_sharding.metadata()); } // Try to merge with sharding from other operands if they can improve // current sharding. const auto* reduce = Cast<const HloReduceInstruction>(&user); for (const HloInstruction* operand : reduce->inputs()) { if (operand != &instruction && operand->has_sharding()) { hlo_sharding_util::MergeShardingIfCompatible( operand->sharding(), user_sharding.NumTiles() + 1, &user_sharding); } } return user_sharding; } case HloOpcode::kSort: { HloSharding user_sharding = user.sharding(); if (user_sharding.IsTuple()) { return user_sharding.GetSubSharding(user.shape(), {user.operand_index(&instruction)}); } return user_sharding; } case HloOpcode::kReverse: { return hlo_sharding_util::ReverseSharding(user.sharding(), user.dimensions()); } case HloOpcode::kOutfeed: { if (&instruction != user.operand(0)) { return std::nullopt; } std::vector<Shape> operand_shapes(user.operand_count()); for (int i = 0; i < user.operand_count(); ++i) { operand_shapes[i] = user.operand(i)->shape(); } return user.sharding().GetSubSharding( ShapeUtil::MakeTupleShape(operand_shapes), {0}); } case HloOpcode::kGather: { if (&instruction == user.operand(1)) { return hlo_sharding_util:: GatherIndexShardingFromOutputIndexPassthroughDimensions( user.sharding(), &user); } if (is_spmd) { return hlo_sharding_util::GatherOperandShardingFromOutput( user.sharding(), user, call_graph); } return std::nullopt; } case HloOpcode::kScatter: { auto& scatter_user = *Cast<HloScatterInstruction>(&user); const int64_t operand_count = scatter_user.scatter_operand_count(); auto scatter_operands = scatter_user.scatter_operands(); auto scatter_indices = scatter_user.scatter_indices(); auto scatter_updates = scatter_user.scatter_updates(); // Infer sharding for scatter operand. const int64_t operand_index = absl::c_find(scatter_operands, &instruction) - scatter_operands.cbegin(); if (operand_index < operand_count) { return user.sharding().IsTuple() ? user.sharding().GetSubSharding( user.shape(), {operand_index}) : user.sharding(); } // Infer sharding for scatter indices. if (&instruction == scatter_indices) { std::vector<const HloInstruction*> partitioned_updates; for (const HloInstruction* update : scatter_updates) { if (hlo_sharding_util::IsSpatiallyPartitioned(update)) { partitioned_updates.push_back(update); } } if (partitioned_updates.empty()) { return std::nullopt; } std::vector<HloSharding> shardings; absl::c_transform( partitioned_updates, std::back_inserter(shardings), [&scatter_user](const HloInstruction* update) { return hlo_sharding_util:: ScatterIndexShardingFromUpdateIndexPassthroughDimensions( update->sharding(), &scatter_user); }); return hlo_sharding_util::FindCommonSharding(shardings); } // Infer sharding for scatter update. const int64_t update_index = absl::c_find(scatter_updates, &instruction) - scatter_updates.cbegin(); CHECK_LE(update_index, operand_count); auto from_indices = hlo_sharding_util::IsSpatiallyPartitioned(scatter_indices) ? hlo_sharding_util:: ScatterUpdateShardingFromIndexIndexPassthroughDimensions( scatter_indices->sharding(), &scatter_user) : HloSharding::Replicate(); if (is_spmd) { auto from_output = hlo_sharding_util::ScatterUpdateShardingFromOutput( user.sharding().IsTuple() ? user.sharding().GetSubSharding(user.shape(), {update_index}) : user.sharding(), scatter_user, call_graph); if (from_output.has_value()) { // Use sharding from output as primary sharding since it prioritize // parallel sharding first as this is how it is in spmd_partitioner. hlo_sharding_util::MergeShardingIfCompatible( from_indices, from_output->NumTiles() + 1, &*from_output); if (!from_output->IsTileMaximal()) { return from_output; } } } if (!from_indices.IsTileMaximal()) { return from_indices; } return std::nullopt; } case HloOpcode::kCustomCall: { bool compatible_shapes = ShapeUtil::CompatibleIgnoringElementType( instruction.shape(), user.shape()); if (!compatible_shapes) { // Incompatible shapes, we will not propagate sharding. return std::nullopt; } if (!sharding_helper) { // No available sharding helper and shapes are compatible, we will // propagate sharding. return user.sharding(); } if (sharding_helper->CanPropagateShardingToOperands(&user)) { return user.sharding(); } return std::nullopt; } default: { // If the user output shape is compatible with the current instruction // shape excluding element type and the current instruction is supported // by spatial partitioning, then the user sharding can be used for // propagation to the current instruction. if (ShapeUtil::CompatibleIgnoringElementType(instruction.shape(), user.shape())) { return user.sharding(); } return std::nullopt; } } } [&scatter_user](const HloInstruction* update) { return hlo_sharding_util:: ScatterIndexShardingFromUpdateIndexPassthroughDimensions( update->sharding(), &scatter_user); }); bool AggressiveConcatOperandShardingCanPassThrough( const HloInstruction* concat_operand) { return ( hlo_sharding_util::IsSpatiallyPartitioned(concat_operand) && (concat_operand->has_sharding() && concat_operand->sharding().NumTiles() > 1) && concat_operand->opcode() == HloOpcode::kReshape && (concat_operand->operand(0)->opcode() == HloOpcode::kParameter || concat_operand->operand(0)->opcode() == HloOpcode::kGetTupleElement)); } bool InferDynamicSliceOrDynamicUpdateSliceShardingFromOperands( HloInstruction* instruction, int64_t aggressiveness, bool may_combine_partial_sharding) { const HloInstruction* operand = instruction->opcode() == HloOpcode::kDynamicSlice ? instruction->operand(0) : instruction->operand(1); auto slice_dim_is_sharded = [&]() { if (!hlo_sharding_util::IsSpatiallyPartitioned(operand) || operand->sharding().IsManual() || operand->sharding().NumTiles() == 1) { return false; } for (int64_t i = 0; i < instruction->shape().rank(); ++i) { const auto& tile_assignment = operand->sharding().tile_assignment(); if (tile_assignment.dim(i) > 1 && instruction->shape().dimensions(i) != operand->shape().dimensions(i)) { return true; } } return false; }; // Do not pass through sharding annotation at the first iteration // if slice dim is sharded. if (aggressiveness == 0 && slice_dim_is_sharded()) { return false; } auto propagate_slicing = [&]() { if (!hlo_sharding_util::IsSpatiallyPartitioned(operand)) { return false; } if (slice_dim_is_sharded()) { return false; } return MaybeImproveInstructionSharding( operand->sharding(), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); }; auto propagate_base = [&]() { if (instruction->opcode() != HloOpcode::kDynamicUpdateSlice) { return false; } if (!hlo_sharding_util::IsSpatiallyPartitioned(instruction->operand(0))) { return false; } return MaybeImproveInstructionSharding(instruction->operand(0)->sharding(), instruction, may_combine_partial_sharding); }; bool changed = propagate_slicing(); changed |= propagate_base(); return changed; } auto slice_dim_is_sharded = [&]() { if (!hlo_sharding_util::IsSpatiallyPartitioned(operand) || operand->sharding().IsManual() || operand->sharding().NumTiles() == 1) { return false; } for (int64_t i = 0; i < instruction->shape().rank(); ++i) { const auto& tile_assignment = operand->sharding().tile_assignment(); if (tile_assignment.dim(i) > 1 && instruction->shape().dimensions(i) != operand->shape().dimensions(i)) { return true; } } return false; }; auto propagate_slicing = [&]() { if (!hlo_sharding_util::IsSpatiallyPartitioned(operand)) { return false; } if (slice_dim_is_sharded()) { return false; } return MaybeImproveInstructionSharding( operand->sharding(), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); }; auto propagate_base = [&]() { if (instruction->opcode() != HloOpcode::kDynamicUpdateSlice) { return false; } if (!hlo_sharding_util::IsSpatiallyPartitioned(instruction->operand(0))) { return false; } return MaybeImproveInstructionSharding(instruction->operand(0)->sharding(), instruction, may_combine_partial_sharding); }; bool ShardingPropagation::InferShardingFromShardGroup( HloInstruction* instruction, const ComputationMap& computation_map, int64_t aggressiveness, const absl::flat_hash_set<HloInstruction*>& shard_group) { if (!CanPropagateThroughAtAggressiveLevel(*instruction, aggressiveness)) { return false; } // Do not change manual sharding. if (instruction->has_sharding() && instruction->sharding().IsManual()) { return false; } // Do not propagate sharding to ShardBarrierTo custom-call. if (instruction->IsCustomCall(spmd::kShardBarrierTo)) { return false; } // Propagate manual sharding. if (!instruction->has_sharding() || instruction->sharding().IsTileMaximal()) { for (const HloInstruction* member : shard_group) { if (!member->has_sharding() || !member->sharding().IsManual() || member == instruction) { continue; } instruction->set_sharding(member->sharding()); return true; } } const bool may_combine_partial_sharding = is_spmd_ && aggressiveness > 0; bool changed = false; for (const HloInstruction* member : shard_group) { // Do not propagate sharding from ShardBarrierFrom custom-call. if (member == instruction || member->IsCustomCall(spmd::kShardBarrierFrom)) { continue; } changed |= MaybeImproveInstructionSharding(member->sharding(), instruction, may_combine_partial_sharding); } return changed; } bool ShardingPropagation::InferShardingFromOperands( HloInstruction* instruction, const ComputationMap& computation_map, int64_t aggressiveness, const CallGraph& call_graph, const absl::flat_hash_set<absl::string_view>& execution_threads) { if (!CanPropagateThroughAtAggressiveLevel(*instruction, aggressiveness)) { return false; } // Do not change manual sharding. if (instruction->has_sharding() && instruction->sharding().IsManual()) { return false; } // Propagate manual sharding. Avoid tuple shaped HLOs that group independent // together. Reduce, ReduceWindow, and Sort can be tuples but the elements // are correlated, so we propagate manual sharding through them. // For custom-calls with manual operand, the default propagation logic will // just assign manual to the whole custom-call. const bool custom_call_condition = instruction->opcode() == HloOpcode::kCustomCall && instruction->shape().IsTuple(); // For asynchronous instructions with manual operand, we assign manual to the // whole instructions if the async_execution_thread is not in the // execution_threads. const bool async_instr_condition = instruction->IsAsynchronous() && !HloInstruction::IsThreadIncluded(instruction->async_execution_thread(), execution_threads); if ((!instruction->has_sharding() || instruction->sharding().IsTileMaximal()) && (instruction->shape().IsArray() || instruction->opcode() == HloOpcode::kReduce || instruction->opcode() == HloOpcode::kSort || instruction->opcode() == HloOpcode::kReduceWindow || custom_call_condition || async_instr_condition)) { for (const HloInstruction* op : instruction->operands()) { if (!op->has_sharding() || !op->sharding().IsManual()) continue; // Do not pass through manual sharding to SPMDShardToFullShape. if (instruction->IsCustomCall("SPMDShardToFullShape")) { return false; } // Do not pass through manual sharding to concat or dynamic slice when // aggressiveneess is 0. if (aggressiveness == 0 && (instruction->opcode() == HloOpcode::kConcatenate || instruction->opcode() == HloOpcode::kDynamicSlice)) { return false; } instruction->set_sharding( HloSharding::Manual(op->sharding().metadata()) .NormalizeTupleSharding(instruction->shape())); return true; } } const bool may_combine_partial_sharding = is_spmd_ && aggressiveness > 0; if (!SupportSpatialPartitioning( instruction, computation_map, is_spmd_, allow_spmd_sharding_propagation_to_output_, /*allow_spmd_sharding_propagation_to_parameters=*/false, sharding_helper_.get())) { // If an array shaped HLO doesn't support spatial partitioning but at least // one of its operand is replicated then we make the HLO replicated as well. if (instruction->shape().IsTuple() || instruction->operand_count() == 0 || instruction == instruction->parent()->root_instruction() || instruction->HasSideEffect()) { return false; } for (const HloInstruction* op : instruction->operands()) { if (op->has_sharding() && op->sharding().IsTileMaximal() && !op->sharding().HasUniqueDevice()) { return MaybeImproveInstructionSharding(op->sharding(), instruction, may_combine_partial_sharding); } } return false; } auto get_maybe_tuple_sharding = [&](HloSharding sharding) { if (instruction->shape().IsArray()) { return sharding; } std::vector<HloSharding> tuple(instruction->shape().tuple_shapes_size(), std::move(sharding)); return HloSharding::Tuple(instruction->shape(), tuple); }; switch (instruction->opcode()) { case HloOpcode::kGetTupleElement: { const HloInstruction* operand = instruction->operand(0); if (!hlo_sharding_util::IsSpatiallyPartitioned(operand)) { return false; } HloSharding new_sharding = operand->sharding().GetSubSharding( operand->shape(), {instruction->tuple_index()}); if (new_sharding.IsManual()) { instruction->set_sharding(std::move(new_sharding)); return true; } return MaybeImproveInstructionSharding( std::move(new_sharding), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); } case HloOpcode::kTuple: { if (absl::c_none_of( instruction->operands(), [](const HloInstruction* hlo) { return hlo_sharding_util::IsSpatiallyPartitioned(hlo); })) { // None of the operands have a spatially partitioned sharding. return false; } const Shape& shape = instruction->shape(); // Go through each operand and if the operand has a sharding that is // better than the current sharding for that tuple element then update // it. If the current sharding does not exist, assume its replicated. std::vector<HloSharding> sub_shardings; if (instruction->has_sharding()) { sub_shardings = instruction->sharding().tuple_elements(); } else { // If instruction does not have a sharding, assume its replicated to // allow refinement. sub_shardings.assign(HloSharding::RequiredLeaves(shape), HloSharding::Replicate()); } // This is required to allow manual sharding on operands to be propagated // to the tuple. hlo_sharding_util::IsShardingMoreSpecific() returns false // if any of the shardings involved is manual, so using it directly will // prevent manual sharding on an operand to be propagated to the tuple // when it has no existing sharding. auto is_more_specific = [instruction](const HloSharding& operand_sharding, const HloSharding& existing) { // If the instruction originally had no sharding, always prefer operand // sharding. return !instruction->has_sharding() || hlo_sharding_util::IsShardingMoreSpecific(operand_sharding, existing); }; int64_t sub_sharding_index = 0; for (int64_t i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const HloInstruction* operand = instruction->operand(i); if (operand->has_sharding()) { if (operand->shape().IsTuple()) { for (int64_t j = 0, e = ShapeUtil::GetLeafCount(operand->shape()); j < e; ++j) { if (is_more_specific(operand->sharding().tuple_elements()[j], sub_shardings[sub_sharding_index + j])) { sub_shardings[sub_sharding_index + j] = operand->sharding().tuple_elements()[j]; } } } else { std::optional<HloSharding> op_sharding = hlo_sharding_util::GetOutputSharding(operand); CHECK(op_sharding.has_value()) << "Expected sharding for " << operand->ToString(); if (is_more_specific(op_sharding.value(), sub_shardings[sub_sharding_index])) { sub_shardings[sub_sharding_index] = op_sharding.value(); } } } sub_sharding_index += ShapeUtil::GetLeafCount(operand->shape()); } HloSharding new_sharding = HloSharding::Tuple(shape, sub_shardings); if (!instruction->has_sharding() || new_sharding != instruction->sharding()) { instruction->set_sharding(std::move(new_sharding)); return true; } return false; } case HloOpcode::kReduce: { // Reduce could have a tuple shape, where the first half of operands are // the arrays to reduce, and the second half of operands are the init // values. return InferReduceShardingFromOperand( instruction, may_combine_partial_sharding, is_spmd_); } case HloOpcode::kBroadcast: { // Make forward propagation through broadcast low priority to avoid // resharding after broadcast. if (aggressiveness < 3) { return false; } const HloInstruction* op = instruction->operand(0); if (!hlo_sharding_util::IsSpatiallyPartitioned(op) || op->sharding().IsReplicated()) { return false; } // The output will be tiled along the broadcasted dimension the same way // as the input for the broadcast while the other dimensions are kept // non-tiled. std::vector<int64_t> target_tile_assignment_dimensions; const auto& dimensions = instruction->dimensions(); for (int64_t i = 0; i < instruction->shape().rank(); ++i) { auto it = absl::c_find(dimensions, i); if (it == dimensions.end()) { target_tile_assignment_dimensions.push_back(1); } else { const int64_t source_dim = std::distance(dimensions.begin(), it); target_tile_assignment_dimensions.push_back( op->sharding().tile_assignment().dim(source_dim)); } } for (int64_t i = op->sharding().TiledDataRank(); i < op->sharding().tile_assignment().num_dimensions(); ++i) { target_tile_assignment_dimensions.push_back( op->sharding().tile_assignment().dim(i)); } auto new_tile_assignment = op->sharding().tile_assignment().Reshape( target_tile_assignment_dimensions); HloSharding new_sharding = op->sharding().ReplicateOnLastTileDim() ? HloSharding::PartialTile(new_tile_assignment, op->sharding().metadata()) : HloSharding::Subgroup(new_tile_assignment, op->sharding().subgroup_types(), op->sharding().metadata()); return MaybeImproveInstructionSharding( std::move(new_sharding), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ComputeNonRootUsers(instruction) == 1); } case HloOpcode::kConcatenate: { const HloInstruction* operand = PickRepresentativeOperand(instruction); if (!operand || !hlo_sharding_util::IsSpatiallyPartitioned(operand)) { return false; } if (aggressiveness == 0) { for (const HloInstruction* concat_operand : instruction->operands()) { if (!AggressiveConcatOperandShardingCanPassThrough(concat_operand)) { return false; } const auto& tile_assignment = concat_operand->sharding().tile_assignment(); for (int64_t i = 0; i < instruction->shape().rank(); ++i) { if (absl::c_linear_search(instruction->dimensions(), i) && tile_assignment.dim(i) > 1) { return false; } } } } return MaybeImproveInstructionSharding( operand->sharding(), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ComputeNonRootUsers(instruction) == 1); } case HloOpcode::kConvolution: return InferConvolutionShardingFromOperands( instruction, call_graph, aggressiveness, may_combine_partial_sharding, is_spmd_); case HloOpcode::kTranspose: { const HloInstruction* input = instruction->operand(0); if (!hlo_sharding_util::IsSpatiallyPartitioned(input)) { return false; } HloSharding sharding = hlo_sharding_util::TransposeSharding( input->sharding(), instruction->dimensions()); return MaybeImproveInstructionSharding( std::move(sharding), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ComputeNonRootUsers(instruction) == 1); } case HloOpcode::kReduceWindow: { auto* reduce_window = Cast<HloReduceWindowInstruction>(instruction); auto has_dilation = [](const WindowDimension& dimensions) { return dimensions.base_dilation() > 1 || dimensions.window_dilation() > 1; }; if (absl::c_any_of(instruction->window().dimensions(), has_dilation)) { VLOG(2) << "Not applying sharding to reduce window because dilatation " "isn't supported yet: " << reduce_window->ToString(); return false; } bool changed = false; for (HloInstruction* operand : reduce_window->inputs()) { if (!hlo_sharding_util::IsSpatiallyPartitioned(operand)) { continue; } changed |= MaybeImproveInstructionSharding( get_maybe_tuple_sharding(operand->sharding()), reduce_window, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); } return changed; } case HloOpcode::kSelectAndScatter: { // Shard according to first operand, as output keeps the same shape. const HloInstruction* lhs = instruction->operand(0); if (!hlo_sharding_util::IsSpatiallyPartitioned(lhs)) { return false; } auto has_base_dilation = [](const WindowDimension& dimensions) { return dimensions.base_dilation() > 1; }; if (absl::c_any_of(instruction->window().dimensions(), has_base_dilation)) { VLOG(2) << "Not applying sharding to select-and-scatter because " "base dilation isn't supported yet: " << instruction->ToString(); return false; } return MaybeImproveInstructionSharding( lhs->sharding(), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ComputeNonRootUsers(instruction) == 1); } case HloOpcode::kReshape: { if (!hlo_sharding_util::IsSpatiallyPartitioned(instruction->operand(0))) { return false; } HloSharding new_sharding = hlo_sharding_util::PropagateShardingThroughReshape( instruction->operand(0)->shape(), instruction->shape(), instruction->operand(0)->sharding()); return MaybeImproveInstructionSharding( std::move(new_sharding), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); return false; } case HloOpcode::kReverse: { const HloInstruction* operand = instruction->operand(0); if (!hlo_sharding_util::IsSpatiallyPartitioned(operand)) { return false; } return MaybeImproveInstructionSharding( hlo_sharding_util::ReverseSharding(operand->sharding(), instruction->dimensions()), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ComputeNonRootUsers(instruction) == 1); } case HloOpcode::kDot: { const auto& dnums = dot_as_convolution_util::ParseDotGeneralFromDot(instruction); return InferDotShardingFromOperands(instruction, call_graph, dnums, may_combine_partial_sharding, is_spmd_); } case HloOpcode::kParameter: { auto parent_it = computation_map.find(instruction->parent()); if (parent_it == computation_map.end()) { return false; } const HloInstruction* parent = parent_it->second; switch (parent->opcode()) { case HloOpcode::kConditional: { for (int64_t i = 1; i < parent->operand_count(); ++i) { if (parent->called_computations()[i - 1] == instruction->parent()) { if (parent->operand(i)->has_sharding()) { return MaybeImproveInstructionSharding( parent->operand(i)->sharding(), instruction, may_combine_partial_sharding); } return false; } } return false; } case HloOpcode::kCall: { int64_t i = instruction->parameter_number(); if (parent->operand(i)->has_sharding()) { return MaybeImproveInstructionSharding( parent->operand(i)->sharding(), instruction, may_combine_partial_sharding); } return false; } default: return false; } } case HloOpcode::kSort: { const HloInstruction* operand = PickRepresentativeOperand(instruction); if (!operand || !hlo_sharding_util::IsSpatiallyPartitioned(operand)) { return false; } HloSortInstruction* sort = DynCast<HloSortInstruction>(instruction); CHECK(sort); const int64_t sort_dim = sort->sort_dimension(); if (!operand->sharding().IsTileMaximal() && operand->sharding().tile_assignment().dim(sort_dim) != 1) { // In case of a sort operand sharded along the sort dimension, the // sharding is propagated only if there exists a free (unsharded) // dimension that we can later move the sharding into. if (!hlo_sharding_util::IsSortOperandShardingMovable(operand, sort_dim)) return false; } if (instruction->shape().IsTuple()) { return MaybeImproveInstructionSharding( HloSharding::SingleTuple(instruction->shape(), operand->sharding()), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); } else { return MaybeImproveInstructionSharding( operand->sharding(), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); } } case HloOpcode::kDynamicSlice: case HloOpcode::kDynamicUpdateSlice: { return InferDynamicSliceOrDynamicUpdateSliceShardingFromOperands( instruction, aggressiveness, may_combine_partial_sharding); } case HloOpcode::kGather: { bool changed = false; if (hlo_sharding_util::IsSpatiallyPartitioned(instruction->operand(1))) { HloSharding new_sharding = hlo_sharding_util:: GatherOutputShardingFromIndexIndexPassthroughDimensions( instruction->operand(1)->sharding(), instruction); changed |= MaybeImproveInstructionSharding( std::move(new_sharding), instruction, may_combine_partial_sharding); } if (is_spmd_) { auto gather_parallel_dims = hlo_sharding_util::GetGatherParallelBatchDims(*instruction, call_graph); if (gather_parallel_dims) { changed |= InferGatherParallelShardingFromOperands( instruction, *gather_parallel_dims, may_combine_partial_sharding); } if (hlo_sharding_util::IsSpatiallyPartitioned( instruction->operand(0))) { absl::Span<const int64_t> operand_parallel_dims; if (gather_parallel_dims) { operand_parallel_dims = absl::MakeConstSpan( gather_parallel_dims->operand_parallel_dims); } HloSharding filtered_operand_sharding = hlo_sharding_util::PartiallyReplicateTiledShardingOnDims( instruction->operand(0)->sharding(), operand_parallel_dims); auto maybe_from_data = hlo_sharding_util:: GatherOutputShardingFromOperandOperandPassthroughDimensions( filtered_operand_sharding, *instruction); if (maybe_from_data) { changed |= MaybeImproveInstructionSharding( std::move(*maybe_from_data), instruction, may_combine_partial_sharding); } } } return changed; } case HloOpcode::kScatter: { auto& scatter = *Cast<HloScatterInstruction>(instruction); const int64_t operand_count = scatter.scatter_operand_count(); auto scatter_operands = scatter.scatter_operands(); auto scatter_indices = scatter.scatter_indices(); auto scatter_updates = scatter.scatter_updates(); bool changed = false; if (is_spmd_) { for (int64_t i = 0; i != operand_count; ++i) { if (hlo_sharding_util::IsSpatiallyPartitioned(scatter_operands[i])) { changed |= MaybeImproveInstructionSubSharding( scatter_operands[i]->sharding(), instruction, {i}, may_combine_partial_sharding); } } if (!hlo_sharding_util::IsSpatiallyPartitioned(scatter_indices) && absl::c_none_of(scatter_updates, [](const HloInstruction* update) { return hlo_sharding_util::IsSpatiallyPartitioned(update); })) { return changed; } auto scatter_parallel_dims = hlo_sharding_util::GetScatterParallelBatchDims(*instruction, call_graph); if (scatter_parallel_dims) { changed |= InferScatterParallelShardingFromOperands( instruction, *scatter_parallel_dims, may_combine_partial_sharding); } for (int64_t i = 0; i != operand_count; ++i) { if (hlo_sharding_util::IsSpatiallyPartitioned(scatter_updates[i])) { auto maybe_from_update = hlo_sharding_util::ScatterOutputShardingFromUpdate( scatter_updates[i]->sharding(), scatter); if (maybe_from_update) { changed |= MaybeImproveInstructionSubSharding( std::move(*maybe_from_update), instruction, {i}, may_combine_partial_sharding); } } } } else { for (int64_t i = 0; i != operand_count; ++i) { changed |= MaybeImproveInstructionSubSharding( HloSharding::Replicate(), instruction, {i}, may_combine_partial_sharding); } } return changed; } case HloOpcode::kWhile: { if (!instruction->operand(0)->has_sharding()) { return false; } auto sharding = instruction->operand(0)->sharding(); if (instruction->has_sharding()) { hlo_sharding_util::MergeSharding(instruction->sharding(), &sharding, may_combine_partial_sharding); } return MaybeImproveInstructionSharding(std::move(sharding), instruction, may_combine_partial_sharding); } case HloOpcode::kCustomCall: { HloSharding inferred_operand_sharding = HloSharding::Replicate(); if (auto* partitioner = GetCustomCallPartitioner(instruction->custom_call_target()); partitioner && partitioner->IsCustomCallShardable(instruction)) { if (auto sharding = partitioner->InferShardingFromOperands(instruction)) { inferred_operand_sharding = *sharding; } else { return false; } } else if (sharding_helper_->IsCustomCallShardable(instruction)) { if (auto sharding = sharding_helper_->InferShardingFromOperands(instruction)) { inferred_operand_sharding = *sharding; } else { return false; } } else { const HloInstruction* operand = PickRepresentativeOperand(instruction); if (!operand || !hlo_sharding_util::IsSpatiallyPartitioned(operand)) { return false; } inferred_operand_sharding = operand->sharding(); } return MaybeImproveInstructionSharding( inferred_operand_sharding, instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ComputeNonRootUsers(instruction) == 1); } default: { if (instruction->IsElementwise() && may_combine_partial_sharding) { bool changed = false; for (auto operand : instruction->operands()) { if (hlo_sharding_util::IsSpatiallyPartitioned(operand)) { if (instruction->opcode() == HloOpcode::kRng) { // Rng is considered elementwise but has operands with different // shapes. changed |= MaybeImproveInstructionSharding( hlo_sharding_util::ReplicateAllDataDims( operand->sharding(), instruction->shape().rank()), instruction, may_combine_partial_sharding, ComputeNonRootUsers(instruction) == 1); continue; } changed |= MaybeImproveInstructionSharding( operand->sharding(), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ instruction->operands().size() == 1 && ComputeNonRootUsers(instruction) == 1); } } return changed; } const HloInstruction* operand = PickRepresentativeOperand(instruction); if (!operand || !hlo_sharding_util::IsSpatiallyPartitioned(operand)) { return false; } return MaybeImproveInstructionSharding( operand->sharding(), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ComputeNonRootUsers(instruction) == 1); } } return false; } // NOLINT(readability/fn_size) auto get_maybe_tuple_sharding = [&](HloSharding sharding) { if (instruction->shape().IsArray()) { return sharding; } std::vector<HloSharding> tuple(instruction->shape().tuple_shapes_size(), std::move(sharding)); return HloSharding::Tuple(instruction->shape(), tuple); }; auto is_more_specific = [instruction](const HloSharding& operand_sharding, const HloSharding& existing) { // If the instruction originally had no sharding, always prefer operand // sharding. return !instruction->has_sharding() || hlo_sharding_util::IsShardingMoreSpecific(operand_sharding, existing); }; VLOG(2) << "Not applying sharding to reduce window because dilatation " VLOG(2) << "Not applying sharding to select-and-scatter because " bool ShardingPropagation::InferShardingFromUsers( HloInstruction* instruction, const ShardingPropagation::ComputationMap& computation_map, int64_t aggressiveness, bool is_spmd, const CustomCallShardingHelper* sharding_helper, const CallGraph& call_graph) { if (aggressiveness < 2 && instruction->opcode() == HloOpcode::kBroadcast) { return false; } // Do not change manual sharding. if (instruction->has_sharding() && instruction->sharding().IsManual()) { return false; } // Propagate manual sharding. if (!instruction->has_sharding() || instruction->sharding().IsTileMaximal()) { for (const HloInstruction* user : instruction->users()) { if (!user->has_sharding() || user->IsCustomCall("SPMDFullToShardShape")) continue; if (instruction->shape().IsArray() && user->sharding().IsManual()) { instruction->set_sharding( HloSharding::Manual(user->sharding().metadata())); return true; } else { std::optional<HloSharding> user_sharding = ShardingPropagation::GetShardingFromUser( *instruction, *user, aggressiveness, is_spmd, call_graph, sharding_helper); if (user_sharding && user_sharding->IsManual()) { instruction->set_sharding(std::move(*user_sharding)); return true; } } } } if (!SupportSpatialPartitioning( instruction, computation_map, is_spmd, /*allow_spmd_sharding_propagation_to_output=*/false, allow_spmd_sharding_propagation_to_parameters_, sharding_helper)) { return false; } bool improved_sharding = false; const bool may_combine_partial_sharding = is_spmd && aggressiveness > 0; for (const HloInstruction* user : instruction->users()) { std::optional<HloSharding> user_sharding = ShardingPropagation::GetShardingFromUser(*instruction, *user, aggressiveness, is_spmd, call_graph, sharding_helper); if (user_sharding && instruction->opcode() == HloOpcode::kCustomCall) { if (auto* partitioner = GetCustomCallPartitioner(instruction->custom_call_target())) { if (partitioner->IsCustomCallShardable(instruction)) { user_sharding = partitioner->PropagateUserSharding(instruction, user, *user_sharding); } } else if (sharding_helper->IsCustomCallShardable(instruction)) { user_sharding = sharding_helper->PropagateUserSharding( instruction, user, *user_sharding); } } if (user_sharding) { improved_sharding |= MaybeImproveInstructionSharding( std::move(*user_sharding), instruction, may_combine_partial_sharding); } } return improved_sharding; } absl::StatusOr<bool> ShardingPropagation::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { // Register custom-call partitioner for SharBarrierFrom and ShardBarrierTo. ABSL_CONST_INIT static absl::once_flag did_registration; absl::call_once(did_registration, [] { RegisterCustomCallPartitioner( spmd::kShardBarrierFrom, std::make_unique<spmd::ShardBarrierFromPartitioner>()); RegisterCustomCallPartitioner( spmd::kShardBarrierTo, std::make_unique<spmd::ShardBarrierToPartitioner>()); }); std::optional<absl::flat_hash_map<const HloInstruction*, HloSharding>> original_sharding; bool any_changed = false; // Preprocessing for CSE prevention propagation: record the original shardings // so that we can revert to them at the end, and only keep those on CSE // prevention instructions. if (cse_prevention_only_) { original_sharding.emplace(); for (auto computation : module->computations(execution_threads)) { for (auto instruction : computation->instructions()) { if (instruction->has_sharding()) { original_sharding->emplace(instruction, instruction->sharding()); } } } } else { // The current pass is not for CSE prevention, but we remove the shardings // added by previous passes for CSE prevention. for (auto computation : module->computations(execution_threads)) { for (auto instruction : computation->instructions()) { if (instruction->has_sharding() && IsCSEPreventionSharding(instruction->sharding())) { instruction->clear_sharding(); any_changed = true; } } } } any_changed |= propagate_metadata_ ? AssignShardingMetadata(module, execution_threads) : RemoveShardingMetadata(module, execution_threads); absl::flat_hash_map<const HloInstruction*, std::vector<int64_t>> unspecified_dims; std::vector<HloSharding> saved_root_shardings; absl::flat_hash_map<int64_t, HloSharding> saved_parameter_shardings; absl::flat_hash_map<HloInstruction*, int64_t> instruction_to_shard_group_id; absl::flat_hash_map<int64_t, absl::flat_hash_set<HloInstruction*>> shard_group_id_to_shard_as_group; absl::flat_hash_map<int64_t, absl::flat_hash_set<HloInstruction*>> shard_group_id_to_shard_like_group; TF_ASSIGN_OR_RETURN( bool changed, ProcessShardingInstruction( module, execution_threads, !cse_prevention_only_, &unspecified_dims, allow_spmd_sharding_propagation_to_output_ ? &saved_root_shardings : nullptr, allow_spmd_sharding_propagation_to_parameters_ ? &saved_parameter_shardings : nullptr, &instruction_to_shard_group_id, &shard_group_id_to_shard_as_group, &shard_group_id_to_shard_like_group, &allow_spmd_sharding_propagation_to_parameters_vector_)); any_changed |= changed; for (const auto& [shard_group_id, shard_as_group] : shard_group_id_to_shard_as_group) { VLOG(5) << "Shard-As group " << shard_group_id << " contains:"; for (auto instruction : shard_as_group) { VLOG(5) << " " << instruction->ToString(); } } for (const auto& [shard_group_id, shard_like_group] : shard_group_id_to_shard_like_group) { VLOG(5) << "Shard-Like group " << shard_group_id << " contains:"; for (auto instruction : shard_like_group) { VLOG(5) << " " << instruction->ToString(); } } // Check sizes of the given allow_spmd_sharding_propagation vectors if (allow_spmd_sharding_propagation_to_output_) { CHECK(!module->entry_computation()->root_instruction()->has_sharding() || allow_spmd_sharding_propagation_to_output_vector_.size() == 1 || module->entry_computation() ->root_instruction() ->sharding() .tuple_elements() .size() == allow_spmd_sharding_propagation_to_output_vector_.size()) << "allow-spmd-sharding-propagation-to-output-vector's size can be " "either 1 or the number of elements in the root tuple of entry " "computation."; } if (allow_spmd_sharding_propagation_to_parameters_) { auto is_same_sized_tuple = [](HloModule* module, int64_t size) { if (module->entry_computation()->num_parameters() != 1) { return false; } HloInstruction* param = module->entry_computation()->parameter_instruction(0); return param->shape().IsTuple() && size == param->shape().tuple_shapes_size(); }; auto size = allow_spmd_sharding_propagation_to_parameters_vector_.size(); CHECK(size == 1 || size == module->entry_computation()->num_parameters() || is_same_sized_tuple(module, size)) << "allow-spmd-sharding-propagation-to-parameters-vector's size can be " "either 1 or the number of parameters in the entry computation."; } // Association of partitionable embedded computations with their parent // instruction. ComputationMap computation_map; // Instructions that are related through a computation and need to share the // same sharding. auto get_related_instructions = [this](HloInstruction* inst) { if (inst->opcode() == HloOpcode::kWhile) { return std::vector<HloInstruction*>{ inst, inst->while_body()->root_instruction(), inst->while_body()->parameter_instruction(0), inst->while_condition()->parameter_instruction(0)}; } else if (inst->opcode() == HloOpcode::kConditional) { const auto& called_computations = inst->called_computations(); std::vector<HloInstruction*> comps; comps.reserve(called_computations.size() + 1); comps.push_back(inst); for (HloComputation* c : called_computations) { comps.push_back(c->root_instruction()); } return comps; } else if (inst->opcode() == HloOpcode::kCustomCall) { if (sharding_helper_ && sharding_helper_->IsCustomCallShardable(inst)) { return sharding_helper_->GetRelatedInstructions(inst); } else { return std::vector<HloInstruction*>{}; } } else if (inst->opcode() == HloOpcode::kCall) { HloComputation* callee = inst->called_computations().front(); return std::vector<HloInstruction*>{inst, callee->root_instruction()}; } else { CHECK(false); } }; // If instruction is a while, or the root or a parameter of a while body, // then propagate its sharding to the while instruction, to its body root, // and to its condition parameter. std::function<void(HloInstruction*, absl::flat_hash_set<HloInstruction*>*)> maybe_computation_propagation = [&](HloInstruction* instruction, absl::flat_hash_set<HloInstruction*>* changed) { auto propagate_to_instruction = [&](HloInstruction* search_inst) { auto related_instructions = get_related_instructions(search_inst); if (absl::c_count(related_instructions, instruction)) { for (HloInstruction* inst : related_instructions) { if (!inst->has_sharding() || inst->sharding() != instruction->sharding()) { VLOG(2) << "Add computation sharding: " << inst->name() << " " << instruction->sharding().ToString(); inst->copy_sharding(instruction); changed->insert(inst); maybe_computation_propagation(inst, changed); } } } }; if (instruction->opcode() == HloOpcode::kConditional || instruction->opcode() == HloOpcode::kWhile || instruction->opcode() == HloOpcode::kCustomCall || instruction->opcode() == HloOpcode::kCall) { propagate_to_instruction(instruction); } if (instruction->opcode() == HloOpcode::kParameter || instruction->parent()->root_instruction() == instruction) { auto it = computation_map.find(instruction->parent()); if (it != computation_map.end()) { propagate_to_instruction(it->second); } } }; for (auto computation : module->computations(execution_threads)) { for (auto instruction : computation->instructions()) { if (instruction->opcode() == HloOpcode::kWhile) { TF_RETURN_IF_ERROR( CheckAndUpdateDeviceAssignmentsInWhileBody(instruction)); } } } // Populate computation_map in order to associate while bodies to their // while instructions. for (auto computation : module->computations(execution_threads)) { for (auto instruction : computation->instructions()) { if (instruction->opcode() == HloOpcode::kWhile || instruction->opcode() == HloOpcode::kConditional || instruction->opcode() == HloOpcode::kCall) { // Check if any of the related instructions has sharding, in which case // propagate it to the other instructions, so they all share the same // sharding, in case the user didn't shard all of them. We don't check // that user shardings are consistent, because such check is already // done by HLO verifier. const HloInstruction* sharded_inst = nullptr; auto related_instructions = get_related_instructions(instruction); for (auto inst : related_instructions) { if (inst->has_sharding()) { sharded_inst = inst; break; } } if (sharded_inst != nullptr) { // Set the same sharding to all the other related instructions. for (auto inst : related_instructions) { inst->copy_sharding(sharded_inst); } } if (instruction->opcode() == HloOpcode::kWhile) { computation_map[instruction->while_body()] = instruction; } else { for (HloComputation* c : instruction->called_computations()) { computation_map[c] = instruction; } } } } } // Collect all pre-sharded instructions as we aren't allowed to modify their // sharding. absl::flat_hash_set<const HloInstruction*> provided_shardings; for (const HloComputation* computation : module->computations(execution_threads)) { for (const HloInstruction* inst : computation->instructions()) { if (inst->has_sharding() && inst != module->entry_computation()->root_instruction() && inst->opcode() != HloOpcode::kParameter && !inst->sharding().IsUnknown()) { provided_shardings.insert(inst); } } } if (!allow_spmd_sharding_propagation_to_output_ && (!module->entry_computation()->root_instruction()->has_sharding() || !module->entry_computation() ->root_instruction() ->sharding() .IsUnknown())) { // Consider the root instruction of the entry module as one with provided // sharding as its sharding have to match with the one expected by the host. provided_shardings.insert(module->entry_computation()->root_instruction()); } if (!allow_spmd_sharding_propagation_to_parameters_) { for (auto param : module->entry_computation()->parameter_instructions()) { if (param->has_sharding() && !param->sharding().IsUnknown()) { provided_shardings.insert(param); } } } // Replace all unknown shardings with replicated sharding for propagation. for (HloComputation* computation : module->computations(execution_threads)) { auto instructions = computation->MakeInstructionPostOrder(); for (auto it = instructions.rbegin(); it != instructions.rend(); ++it) { HloInstruction* instruction = *it; if (instruction->has_sharding() && instruction->sharding().IsUnknown()) { instruction->set_sharding( HloSharding::Replicate(instruction->sharding().metadata())); } } } // Iterate to a fixpoint that is guaranteed to be reached because we only // strictly improve the sharding of the graph and it can't be improved // indefinitely. int64_t iterations = 0; std::unique_ptr<CallGraph> call_graph = CallGraph::Build(module); auto run_to_fix_point = [&](int64_t aggressiveness, bool propagate_shard_group) { absl::flat_hash_set<const HloInstruction*> already_inferred_from_shard_group; absl::flat_hash_set<const HloInstruction*> already_inferred_from_operands; absl::flat_hash_set<const HloInstruction*> already_inferred_from_users; bool changed_last_iter = true; const bool may_merge_partial = is_spmd_ && aggressiveness > 0; while (changed_last_iter) { changed_last_iter = false; int64_t inferred_from_shard_group_counter = 0; int64_t inferred_from_operand_counter = 0; int64_t inferred_from_user_counter = 0; int64_t instruction_counter = 0; int64_t already_sharded_counter = 0; for (const HloComputation* computation : module->computations(execution_threads)) { VLOG(2) << "Consider computation: " << computation->name(); std::vector<HloInstruction*> instructions = computation->MakeInstructionPostOrder(); instruction_counter += instructions.size(); already_sharded_counter += absl::c_count_if( instructions, [](const HloInstruction* inst) { return inst->has_sharding(); }); auto clear_cache = [&](HloInstruction* hlo, HloInstruction* hlo_for_users = nullptr) { for (auto operand : hlo->operands()) { already_inferred_from_users.erase(operand); } if (hlo_for_users == nullptr) { hlo_for_users = hlo; } for (auto user : hlo_for_users->users()) { already_inferred_from_operands.erase(user); // If the user has called computations, then the parameter // instructions of these called computations are also removed from // already_inferred_from_operands. for (auto c : user->called_computations()) { for (auto parameter : c->parameter_instructions()) { already_inferred_from_operands.erase(parameter); } } } if (instruction_to_shard_group_id.contains(hlo)) { const int64_t shard_group_id = instruction_to_shard_group_id.at(hlo); const absl::flat_hash_set<HloInstruction*>& shard_group = shard_group_id_to_shard_as_group.contains(shard_group_id) ? shard_group_id_to_shard_as_group.at(shard_group_id) : shard_group_id_to_shard_like_group.at(shard_group_id); for (HloInstruction* member : shard_group) { if (member != hlo) { already_inferred_from_shard_group.erase(member); } } } }; // 1. Iterate the shard groups to take shardings from instructions of // the same group. if (propagate_shard_group) { for (HloInstruction* instruction : instructions) { if (already_inferred_from_shard_group.contains(instruction)) { continue; } if (!instruction_to_shard_group_id.contains(instruction)) { continue; } const int64_t shard_group_id = instruction_to_shard_group_id.at(instruction); const absl::flat_hash_set<HloInstruction*>& shard_group = shard_group_id_to_shard_as_group.contains(shard_group_id) ? shard_group_id_to_shard_as_group.at(shard_group_id) : shard_group_id_to_shard_like_group.at(shard_group_id); if (provided_shardings.contains(instruction)) { if (!may_merge_partial) { continue; } auto it = unspecified_dims.find(instruction); if (it != unspecified_dims.end() && InferUnspecifiedDimsFromShardGroup(instruction, it->second, shard_group)) { ++inferred_from_shard_group_counter; VLOG(2) << "Refined partial sharding (shard group): " << instruction->ToString(); clear_cache(instruction); already_inferred_from_shard_group.insert(instruction); changed_last_iter = true; } continue; } already_inferred_from_shard_group.insert(instruction); if (InferShardingFromShardGroup(instruction, computation_map, aggressiveness, shard_group)) { ++inferred_from_shard_group_counter; any_changed = true; VLOG(2) << "Add sharding (shard group): " << instruction->ToString(); absl::flat_hash_set<HloInstruction*> changed_in_comp_prop; maybe_computation_propagation(instruction, &changed_in_comp_prop); clear_cache(instruction); for (auto hlo : changed_in_comp_prop) { clear_cache(hlo); } changed_last_iter = true; } } } // 2. Iterate the HLO graph in post order taking shardings from // operands. for (HloInstruction* instruction : instructions) { if (already_inferred_from_operands.contains(instruction)) { continue; } if (provided_shardings.contains(instruction)) { if (!may_merge_partial) { continue; } auto it = unspecified_dims.find(instruction); HloInstruction* man_conversion_op_after; if (it != unspecified_dims.end() && InferUnspecifiedDimsFromOperand(instruction, it->second, &man_conversion_op_after)) { ++inferred_from_operand_counter; VLOG(2) << "Refined partial sharding (forward-pass): " << instruction->ToString(); clear_cache(instruction, man_conversion_op_after); already_inferred_from_operands.insert(instruction); changed_last_iter = true; } continue; } already_inferred_from_operands.insert(instruction); if (InferShardingFromOperands(instruction, computation_map, aggressiveness, *call_graph, execution_threads)) { ++inferred_from_operand_counter; any_changed = true; VLOG(2) << "Add sharding (forward-pass): " << instruction->ToString(); absl::flat_hash_set<HloInstruction*> changed_in_comp_prop; maybe_computation_propagation(instruction, &changed_in_comp_prop); clear_cache(instruction); for (auto hlo : changed_in_comp_prop) { clear_cache(hlo); } changed_last_iter = true; } } // 3. Iterate the HLO graph in reverse post order taking shardings from // users. for (auto it = instructions.rbegin(); it != instructions.rend(); ++it) { if ((*it)->IsCustomCall("SPMDFullToShardShape") || (*it)->IsCustomCall("SPMDShardToFullShape")) { // The manual conversion op is processed together with the sharding // op before it. If the conversion op is removed from cache, the // sharding op should also be removed. if (!already_inferred_from_users.contains(*it)) { already_inferred_from_users.erase((*it)->operand(0)); } } if (already_inferred_from_users.contains(*it)) { continue; } if (provided_shardings.contains(*it)) { if (!may_merge_partial) { continue; } auto uit = unspecified_dims.find(*it); HloInstruction* man_conversion_op_after; if (uit != unspecified_dims.end() && InferUnspecifiedDimsFromUsers( *it, uit->second, aggressiveness, is_spmd_, &man_conversion_op_after, *call_graph)) { ++inferred_from_user_counter; VLOG(2) << "Refined partial sharding (backward-pass): " << (*it)->ToString(); clear_cache(*it, man_conversion_op_after); already_inferred_from_users.insert(*it); if (man_conversion_op_after != nullptr) { already_inferred_from_users.insert(man_conversion_op_after); } changed_last_iter = true; } continue; } already_inferred_from_users.insert(*it); if (InferShardingFromUsers(*it, computation_map, aggressiveness, is_spmd_, sharding_helper_.get(), *call_graph)) { ++inferred_from_user_counter; any_changed = true; VLOG(2) << "Add sharding (backward-pass): " << (*it)->ToString(); absl::flat_hash_set<HloInstruction*> changed_in_comp_prop; maybe_computation_propagation(*it, &changed_in_comp_prop); clear_cache(*it); for (auto hlo : changed_in_comp_prop) { clear_cache(hlo); } changed_last_iter = true; } } } VLOG(1) << "Sharding propagation iteration " << iterations << ";" << "\n total instructions: " << instruction_counter << "\n instructions already sharded: " << already_sharded_counter << "\n shardings inferred from shard group: " << inferred_from_shard_group_counter << "\n shardings inferred from operands: " << inferred_from_operand_counter << "\n shardings inferred from users: " << inferred_from_user_counter << "\n aggressiveness: " << aggressiveness; ++iterations; } return absl::OkStatus(); }; for (int64_t aggressiveness = 0; aggressiveness < 4; ++aggressiveness) { TF_RETURN_IF_ERROR( run_to_fix_point(aggressiveness, /*propagate_shard_group=*/true)); } // Align the shardings from the same shard_as group so that they will adopt // the same sharding. for (const auto& [shard_as_group_id, shard_as_group] : shard_group_id_to_shard_as_group) { // If all the inferred shardings of the instructions from the same shard // group are compatible with each other, then we will merge all of them to // get the most specific sharding. If some of them are not compatible, then // it will just choose the a random sharding among them(say the first one), // with the guarantee that the defaultly chosen sharding will not be from a // ShardBarrierFrom op if there is one within the ShardAs group. HloSharding default_sharding = HloSharding::Replicate(); std::vector<HloSharding> shardings; for (HloInstruction* instruction : shard_as_group) { if (instruction->has_sharding()) { shardings.push_back(instruction->sharding()); if (!instruction->IsCustomCall(spmd::kShardBarrierFrom) && default_sharding.IsReplicated()) { default_sharding = instruction->sharding(); } } } HloSharding common_sharding = hlo_sharding_util::FindCommonSharding(shardings, default_sharding); VLOG(2) << "Aligning shard group: " << shard_as_group_id << " to sharding:" << common_sharding.ToString(); for (HloInstruction* member : shard_as_group) { if (member->IsCustomCall(spmd::kShardBarrierTo)) { continue; } if (provided_shardings.contains(member)) { auto it = unspecified_dims.find(member); if (it != unspecified_dims.end()) { HloSharding partial_replicated = hlo_sharding_util::PartiallyReplicateTiledShardingOnAllDimsExcept( common_sharding, it->second); HloSharding sharding = member->sharding(); if (hlo_sharding_util::MergeShardingIfCompatible( partial_replicated, sharding.NumTiles() + 1, &sharding)) { member->set_sharding(sharding); } } } member->set_sharding(common_sharding); } } // If a ShardBarrierFrom custom-call op is in a shard as group, and relay // the shard as sharding to its original op, do not relay shardings for // ShardbarrierTo op. Then run sharding propagation once more at highest // aggressiveness without propagating shard group. for (HloComputation* computation : module->computations(execution_threads)) { for (HloInstruction* instruction : computation->instructions()) { if (instruction->IsCustomCall(spmd::kShardBarrierFrom) && instruction_to_shard_group_id.contains(instruction) && shard_group_id_to_shard_as_group.contains( instruction_to_shard_group_id.at(instruction))) { HloSharding sharding = instruction->sharding(); hlo_sharding_util::MergeShardingIfCompatible( instruction->mutable_operand(0)->sharding(), sharding.NumTiles(), &sharding); instruction->mutable_operand(0)->set_sharding(std::move(sharding)); } } } TF_RETURN_IF_ERROR( run_to_fix_point(/*aggressiveness=*/3, /*propagate_shard_group=*/false)); // Post-process to remove all "shard-barrier-from" and "shard-barrier-to" // custom-calls. for (HloComputation* computation : module->computations(execution_threads)) { for (HloInstruction* instruction : computation->instructions()) { // If a ShardBarrierFrom custom-call op is in a shard as group, and relay // the shard as sharding to its original op, do not relay shardings for // ShardbarrierTo op. if (instruction->IsCustomCall(spmd::kShardBarrierFrom) && instruction_to_shard_group_id.contains(instruction) && shard_group_id_to_shard_as_group.contains( instruction_to_shard_group_id.at(instruction))) { HloSharding sharding = instruction->sharding(); hlo_sharding_util::MergeShardingIfCompatible( instruction->mutable_operand(0)->sharding(), sharding.NumTiles(), &sharding); instruction->mutable_operand(0)->set_sharding(std::move(sharding)); } if (instruction->IsCustomCall(spmd::kShardBarrierFrom) || instruction->IsCustomCall(spmd::kShardBarrierTo)) { TF_ASSIGN_OR_RETURN(std::ignore, computation->ReplaceInstruction( instruction, instruction->mutable_operand(0), /*preserve_sharding=*/false, /*relay_control_dependency=*/false, /*remove_unused_operands=*/false)); } } } // Post-process for CSE prevention. if (cse_prevention_only_) { for (auto computation : module->computations(execution_threads)) { for (auto instruction : computation->instructions()) { if (!instruction->has_sharding()) { continue; } if (IsCSEPreventionTarget(instruction) && instruction->has_sharding()) { if (!(*original_sharding).contains(instruction)) { // Mark the propagated sharding as for CSE prevention. instruction->set_sharding( SetCSEPreventionSharding(instruction->sharding())); } continue; } auto it = (*original_sharding).find(instruction); if (it != (*original_sharding).end()) { // Revert sharding. instruction->set_sharding(it->second); } else { // Clear sharding. instruction->clear_sharding(); } } } } HloInstruction* root_instruction = module->entry_computation()->root_instruction(); if (saved_root_shardings.size() == allow_spmd_sharding_propagation_to_output_vector_.size() && root_instruction->has_sharding()) { HloSharding root_sharding = root_instruction->sharding(); for (int i = 0; i < saved_root_shardings.size(); ++i) { if (!allow_spmd_sharding_propagation_to_output_vector_[i] && !saved_root_shardings[i].IsUnknown()) { root_sharding.tuple_elements()[i] = saved_root_shardings[i]; } } root_instruction->set_sharding(std::move(root_sharding)); } auto params = module->entry_computation()->parameter_instructions(); if (allow_spmd_sharding_propagation_to_parameters_) { if (allow_spmd_sharding_propagation_to_parameters_vector_.size() == params.size()) { for (int64_t i = 0; i < params.size(); ++i) { if (!allow_spmd_sharding_propagation_to_parameters_vector_[i]) { if (saved_parameter_shardings.contains(i) && !saved_parameter_shardings.at(i).IsUnknown()) { params[i]->set_sharding(saved_parameter_shardings.at(i)); } else { params[i]->clear_sharding(); } } } } else if (params.size() == 1 && saved_parameter_shardings.size() == 1 && params[0]->shape().IsTuple() && params[0]->shape().tuple_shapes_size() == allow_spmd_sharding_propagation_to_parameters_vector_ .size()) { // There is a single parameter which is a tuple with many elements. HloSharding param_sharding = params[0]->sharding(); for (int64_t i = 0; i < params[0]->shape().tuple_shapes_size(); ++i) { HloSharding saved_subsharding = saved_parameter_shardings.at(0).GetSubSharding(params[0]->shape(), {i}); if (!allow_spmd_sharding_propagation_to_parameters_vector_[i] && !saved_subsharding.IsUnknown()) { param_sharding.tuple_elements()[i] = saved_subsharding; } } params[0]->set_sharding(std::move(param_sharding)); } } // Replicate the parameter/output sharding if the propagated sharding does not // evenly partition the parameter/output. std::function<bool(const Shape&, const HloSharding&)> evenly_partitions = [&evenly_partitions](const Shape& shape, const HloSharding& sharding) -> bool { if (!sharding.IsTiled()) { return true; } if (sharding.IsTileMaximal()) { return sharding.IsReplicated(); } if (sharding.IsTuple()) { for (int64_t i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { if (!evenly_partitions(ShapeUtil::GetTupleElementShape(shape, i), sharding.GetSubSharding(shape, {i}))) { return false; } } } for (int64_t i = 0; i < shape.dimensions_size(); ++i) { if (shape.dimensions(i) % sharding.tile_assignment().dim(i) != 0) { return false; } } return true; }; if (allow_spmd_sharding_propagation_to_output_ && root_instruction->has_sharding()) { if (root_instruction->shape().IsTuple() && allow_spmd_sharding_propagation_to_output_vector_.size() == root_instruction->shape().tuple_shapes_size()) { // The output shape is a tuple and sharding propagation is allowed for at // least one of its elements. HloSharding root_sharding = root_instruction->sharding(); for (int64_t i = 0; i < root_instruction->shape().tuple_shapes_size(); ++i) { if (allow_spmd_sharding_propagation_to_output_vector_[i] && !evenly_partitions(root_instruction->shape().tuple_shapes(i), root_sharding.tuple_elements()[i])) { root_sharding.tuple_elements()[i] = HloSharding::Replicate(); } } root_instruction->set_sharding(std::move(root_sharding)); } else if (!root_instruction->shape().IsTuple()) { // The output shape is not tuple and sharding propagation is allowed. if (!evenly_partitions(root_instruction->shape(), root_instruction->sharding())) { root_instruction->set_sharding(HloSharding::Replicate()); } } } if (allow_spmd_sharding_propagation_to_parameters_) { // Sharding propagation is allowed for at least one parameter. if (allow_spmd_sharding_propagation_to_parameters_vector_.size() == params.size()) { for (int64_t i = 0; i < params.size(); ++i) { if (params[i]->has_sharding() && allow_spmd_sharding_propagation_to_parameters_vector_[i] && !evenly_partitions(params[i]->shape(), params[i]->sharding())) { params[i]->set_sharding(HloSharding::Replicate()); } } } else if (params.size() == 1 && params[0]->shape().IsTuple() && params[0]->has_sharding() && params[0]->shape().tuple_shapes_size() == allow_spmd_sharding_propagation_to_parameters_vector_ .size()) { HloSharding param_sharding = params[0]->sharding(); for (int64_t i = 0; i < params[0]->shape().tuple_shapes_size(); ++i) { if (allow_spmd_sharding_propagation_to_parameters_vector_[i] && !evenly_partitions( ShapeUtil::GetSubshapeOneIndex(params[0]->shape(), i), params[0]->sharding().GetSubSharding(params[0]->shape(), {i}))) { param_sharding.tuple_elements()[i] = HloSharding::Replicate(); } } params[0]->set_sharding(std::move(param_sharding)); } } TF_RETURN_IF_ERROR( hlo_sharding_util::CanonicalizeLayoutAfterShardingPropagation( module, allow_spmd_sharding_propagation_to_output_, allow_spmd_sharding_propagation_to_parameters_)); VLOG(1) << "Sharding propagation completed after " << iterations << " iterations"; return any_changed; } absl::call_once(did_registration, [] { RegisterCustomCallPartitioner( spmd::kShardBarrierFrom, std::make_unique<spmd::ShardBarrierFromPartitioner>()); RegisterCustomCallPartitioner( spmd::kShardBarrierTo, std::make_unique<spmd::ShardBarrierToPartitioner>()); }); VLOG(5) << "Shard-As group " << shard_group_id << " contains:"; VLOG(5) << " " << instruction->ToString(); VLOG(5) << "Shard-Like group " << shard_group_id << " contains:"; VLOG(5) << " " << instruction->ToString(); auto is_same_sized_tuple = [](HloModule* module, int64_t size) { if (module->entry_computation()->num_parameters() != 1) { return false; } HloInstruction* param = module->entry_computation()->parameter_instruction(0); return param->shape().IsTuple() && size == param->shape().tuple_shapes_size(); }; auto get_related_instructions = [this](HloInstruction* inst) { if (inst->opcode() == HloOpcode::kWhile) { return std::vector<HloInstruction*>{ inst, inst->while_body()->root_instruction(), inst->while_body()->parameter_instruction(0), inst->while_condition()->parameter_instruction(0)}; } else if (inst->opcode() == HloOpcode::kConditional) { const auto& called_computations = inst->called_computations(); std::vector<HloInstruction*> comps; comps.reserve(called_computations.size() + 1); comps.push_back(inst); for (HloComputation* c : called_computations) { comps.push_back(c->root_instruction()); } return comps; } else if (inst->opcode() == HloOpcode::kCustomCall) { if (sharding_helper_ && sharding_helper_->IsCustomCallShardable(inst)) { return sharding_helper_->GetRelatedInstructions(inst); } else { return std::vector<HloInstruction*>{}; } } else if (inst->opcode() == HloOpcode::kCall) { HloComputation* callee = inst->called_computations().front(); return std::vector<HloInstruction*>{inst, callee->root_instruction()}; } else { CHECK(false); } }; [&](HloInstruction* instruction, absl::flat_hash_set<HloInstruction*>* changed) { auto propagate_to_instruction = [&](HloInstruction* search_inst) { auto related_instructions = get_related_instructions(search_inst); if (absl::c_count(related_instructions, instruction)) { for (HloInstruction* inst : related_instructions) { if (!inst->has_sharding() || inst->sharding() != instruction->sharding()) { VLOG(2) << "Add computation sharding: " << inst->name() << " " << instruction->sharding().ToString(); inst->copy_sharding(instruction); changed->insert(inst); maybe_computation_propagation(inst, changed); } } } }; if (instruction->opcode() == HloOpcode::kConditional || instruction->opcode() == HloOpcode::kWhile || instruction->opcode() == HloOpcode::kCustomCall || instruction->opcode() == HloOpcode::kCall) { propagate_to_instruction(instruction); } if (instruction->opcode() == HloOpcode::kParameter || instruction->parent()->root_instruction() == instruction) { auto it = computation_map.find(instruction->parent()); if (it != computation_map.end()) { propagate_to_instruction(it->second); } } }; auto propagate_to_instruction = [&](HloInstruction* search_inst) { auto related_instructions = get_related_instructions(search_inst); if (absl::c_count(related_instructions, instruction)) { for (HloInstruction* inst : related_instructions) { if (!inst->has_sharding() || inst->sharding() != instruction->sharding()) { VLOG(2) << "Add computation sharding: " << inst->name() << " " << instruction->sharding().ToString(); inst->copy_sharding(instruction); changed->insert(inst); maybe_computation_propagation(inst, changed); } } } }; VLOG(2) << "Add computation sharding: " << inst->name() auto run_to_fix_point = [&](int64_t aggressiveness, bool propagate_shard_group) { absl::flat_hash_set<const HloInstruction*> already_inferred_from_shard_group; absl::flat_hash_set<const HloInstruction*> already_inferred_from_operands; absl::flat_hash_set<const HloInstruction*> already_inferred_from_users; bool changed_last_iter = true; const bool may_merge_partial = is_spmd_ && aggressiveness > 0; while (changed_last_iter) { changed_last_iter = false; int64_t inferred_from_shard_group_counter = 0; int64_t inferred_from_operand_counter = 0; int64_t inferred_from_user_counter = 0; int64_t instruction_counter = 0; int64_t already_sharded_counter = 0; for (const HloComputation* computation : module->computations(execution_threads)) { VLOG(2) << "Consider computation: " << computation->name(); std::vector<HloInstruction*> instructions = computation->MakeInstructionPostOrder(); instruction_counter += instructions.size(); already_sharded_counter += absl::c_count_if( instructions, [](const HloInstruction* inst) { return inst->has_sharding(); }); auto clear_cache = [&](HloInstruction* hlo, HloInstruction* hlo_for_users = nullptr) { for (auto operand : hlo->operands()) { already_inferred_from_users.erase(operand); } if (hlo_for_users == nullptr) { hlo_for_users = hlo; } for (auto user : hlo_for_users->users()) { already_inferred_from_operands.erase(user); // If the user has called computations, then the parameter // instructions of these called computations are also removed from // already_inferred_from_operands. for (auto c : user->called_computations()) { for (auto parameter : c->parameter_instructions()) { already_inferred_from_operands.erase(parameter); } } } if (instruction_to_shard_group_id.contains(hlo)) { const int64_t shard_group_id = instruction_to_shard_group_id.at(hlo); const absl::flat_hash_set<HloInstruction*>& shard_group = shard_group_id_to_shard_as_group.contains(shard_group_id) ? shard_group_id_to_shard_as_group.at(shard_group_id) : shard_group_id_to_shard_like_group.at(shard_group_id); for (HloInstruction* member : shard_group) { if (member != hlo) { already_inferred_from_shard_group.erase(member); } } } }; // 1. Iterate the shard groups to take shardings from instructions of // the same group. if (propagate_shard_group) { for (HloInstruction* instruction : instructions) { if (already_inferred_from_shard_group.contains(instruction)) { continue; } if (!instruction_to_shard_group_id.contains(instruction)) { continue; } const int64_t shard_group_id = instruction_to_shard_group_id.at(instruction); const absl::flat_hash_set<HloInstruction*>& shard_group = shard_group_id_to_shard_as_group.contains(shard_group_id) ? shard_group_id_to_shard_as_group.at(shard_group_id) : shard_group_id_to_shard_like_group.at(shard_group_id); if (provided_shardings.contains(instruction)) { if (!may_merge_partial) { continue; } auto it = unspecified_dims.find(instruction); if (it != unspecified_dims.end() && InferUnspecifiedDimsFromShardGroup(instruction, it->second, shard_group)) { ++inferred_from_shard_group_counter; VLOG(2) << "Refined partial sharding (shard group): " << instruction->ToString(); clear_cache(instruction); already_inferred_from_shard_group.insert(instruction); changed_last_iter = true; } continue; } already_inferred_from_shard_group.insert(instruction); if (InferShardingFromShardGroup(instruction, computation_map, aggressiveness, shard_group)) { ++inferred_from_shard_group_counter; any_changed = true; VLOG(2) << "Add sharding (shard group): " << instruction->ToString(); absl::flat_hash_set<HloInstruction*> changed_in_comp_prop; maybe_computation_propagation(instruction, &changed_in_comp_prop); clear_cache(instruction); for (auto hlo : changed_in_comp_prop) { clear_cache(hlo); } changed_last_iter = true; } } } // 2. Iterate the HLO graph in post order taking shardings from // operands. for (HloInstruction* instruction : instructions) { if (already_inferred_from_operands.contains(instruction)) { continue; } if (provided_shardings.contains(instruction)) { if (!may_merge_partial) { continue; } auto it = unspecified_dims.find(instruction); HloInstruction* man_conversion_op_after; if (it != unspecified_dims.end() && InferUnspecifiedDimsFromOperand(instruction, it->second, &man_conversion_op_after)) { ++inferred_from_operand_counter; VLOG(2) << "Refined partial sharding (forward-pass): " << instruction->ToString(); clear_cache(instruction, man_conversion_op_after); already_inferred_from_operands.insert(instruction); changed_last_iter = true; } continue; } already_inferred_from_operands.insert(instruction); if (InferShardingFromOperands(instruction, computation_map, aggressiveness, *call_graph, execution_threads)) { ++inferred_from_operand_counter; any_changed = true; VLOG(2) << "Add sharding (forward-pass): " << instruction->ToString(); absl::flat_hash_set<HloInstruction*> changed_in_comp_prop; maybe_computation_propagation(instruction, &changed_in_comp_prop); clear_cache(instruction); for (auto hlo : changed_in_comp_prop) { clear_cache(hlo); } changed_last_iter = true; } } // 3. Iterate the HLO graph in reverse post order taking shardings from // users. for (auto it = instructions.rbegin(); it != instructions.rend(); ++it) { if ((*it)->IsCustomCall("SPMDFullToShardShape") || (*it)->IsCustomCall("SPMDShardToFullShape")) { // The manual conversion op is processed together with the sharding // op before it. If the conversion op is removed from cache, the // sharding op should also be removed. if (!already_inferred_from_users.contains(*it)) { already_inferred_from_users.erase((*it)->operand(0)); } } if (already_inferred_from_users.contains(*it)) { continue; } if (provided_shardings.contains(*it)) { if (!may_merge_partial) { continue; } auto uit = unspecified_dims.find(*it); HloInstruction* man_conversion_op_after; if (uit != unspecified_dims.end() && InferUnspecifiedDimsFromUsers( *it, uit->second, aggressiveness, is_spmd_, &man_conversion_op_after, *call_graph)) { ++inferred_from_user_counter; VLOG(2) << "Refined partial sharding (backward-pass): " << (*it)->ToString(); clear_cache(*it, man_conversion_op_after); already_inferred_from_users.insert(*it); if (man_conversion_op_after != nullptr) { already_inferred_from_users.insert(man_conversion_op_after); } changed_last_iter = true; } continue; } already_inferred_from_users.insert(*it); if (InferShardingFromUsers(*it, computation_map, aggressiveness, is_spmd_, sharding_helper_.get(), *call_graph)) { ++inferred_from_user_counter; any_changed = true; VLOG(2) << "Add sharding (backward-pass): " << (*it)->ToString(); absl::flat_hash_set<HloInstruction*> changed_in_comp_prop; maybe_computation_propagation(*it, &changed_in_comp_prop); clear_cache(*it); for (auto hlo : changed_in_comp_prop) { clear_cache(hlo); } changed_last_iter = true; } } } VLOG(1) << "Sharding propagation iteration " << iterations << ";" << "\n total instructions: " << instruction_counter << "\n instructions already sharded: " << already_sharded_counter << "\n shardings inferred from shard group: " << inferred_from_shard_group_counter << "\n shardings inferred from operands: " << inferred_from_operand_counter << "\n shardings inferred from users: " << inferred_from_user_counter << "\n aggressiveness: " << aggressiveness; ++iterations; } return absl::OkStatus(); }; VLOG(2) << "Consider computation: " << computation->name(); auto clear_cache = [&](HloInstruction* hlo, HloInstruction* hlo_for_users = nullptr) { for (auto operand : hlo->operands()) { already_inferred_from_users.erase(operand); } if (hlo_for_users == nullptr) { hlo_for_users = hlo; } for (auto user : hlo_for_users->users()) { already_inferred_from_operands.erase(user); // If the user has called computations, then the parameter // instructions of these called computations are also removed from // already_inferred_from_operands. for (auto c : user->called_computations()) { for (auto parameter : c->parameter_instructions()) { already_inferred_from_operands.erase(parameter); } } } if (instruction_to_shard_group_id.contains(hlo)) { const int64_t shard_group_id = instruction_to_shard_group_id.at(hlo); const absl::flat_hash_set<HloInstruction*>& shard_group = shard_group_id_to_shard_as_group.contains(shard_group_id) ? shard_group_id_to_shard_as_group.at(shard_group_id) : shard_group_id_to_shard_like_group.at(shard_group_id); for (HloInstruction* member : shard_group) { if (member != hlo) { already_inferred_from_shard_group.erase(member); } } } }; VLOG(2) << "Refined partial sharding (shard group): " VLOG(2) << "Add sharding (shard group): " VLOG(2) << "Refined partial sharding (forward-pass): " VLOG(2) << "Add sharding (forward-pass): " VLOG(2) << "Refined partial sharding (backward-pass): " VLOG(2) << "Add sharding (backward-pass): " << (*it)->ToString(); VLOG(1) << "Sharding propagation iteration " << iterations << ";" VLOG(2) << "Aligning shard group: " << shard_as_group_id [&evenly_partitions](const Shape& shape, const HloSharding& sharding) -> bool { if (!sharding.IsTiled()) { return true; } if (sharding.IsTileMaximal()) { return sharding.IsReplicated(); } if (sharding.IsTuple()) { for (int64_t i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { if (!evenly_partitions(ShapeUtil::GetTupleElementShape(shape, i), sharding.GetSubSharding(shape, {i}))) { return false; } } } for (int64_t i = 0; i < shape.dimensions_size(); ++i) { if (shape.dimensions(i) % sharding.tile_assignment().dim(i) != 0) { return false; } } return true; }; VLOG(1) << "Sharding propagation completed after " << iterations
#include "xla/service/sharding_propagation.h" #include <ostream> #include <string> #include <utility> #include <vector> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/log/check.h" #include "absl/log/log.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/ir/hlo_op_metadata.h" #include "xla/hlo/ir/hlo_sharding.h" #include "xla/hlo/transforms/hlo_constant_splitter.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/protobuf_util.h" #include "xla/service/hlo_dce.h" #include "xla/service/hlo_parser.h" #include "xla/tests/hlo_test_base.h" #include "xla/util.h" #include "xla/xla_data.pb.h" #include "tsl/platform/statusor.h" TEST_F(ShardingPropagationTest, PropagateToParametersFull1) { const char* const hlo_string = R"( HloModule module ENTRY %entry { %param0 = f32[4] parameter(0) %param1 = f32[4] parameter(1) ROOT %add = f32[4] add(%param0, %param1), sharding={devices=[4]0,1,2,3} })"; TF_ASSERT_OK_AND_ASSIGN(auto module, ParseAndReturnVerifiedModule(hlo_string)); TF_ASSERT_OK_AND_ASSIGN( bool changed, ShardingPropagation( /*is_spmd=*/true, /*propagate_metadata=*/true, /*allow_spmd_sharding_propagation_to_output=*/{false}, /*allow_spmd_sharding_propagation_to_parameters=*/{true}) .Run(module.get())); XLA_VLOG_LINES(1, module->ToString()); EXPECT_TRUE(changed); EXPECT_THAT(module->entry_computation()->parameter_instruction(0), op::Sharding("{devices=[4]0,1,2,3}")); EXPECT_THAT(module->entry_computation()->parameter_instruction(1), op::Sharding("{devices=[4]0,1,2,3}")); }
ShardingPropagationTest_PropagateToParametersFull2
xla/service/sharding_propagation_test.cc
std::optional<HloSharding> ReturnImprovedSharding( HloSharding sharding, HloInstruction* instruction, bool may_combine_partial_sharding, bool allow_aggressive_resharding = false) { return hlo_sharding_util::ReturnImprovedShardingImpl( std::move(sharding), instruction->has_sharding() ? &instruction->sharding() : nullptr, instruction->shape(), may_combine_partial_sharding, allow_aggressive_resharding); } std::optional<HloSharding> ReturnImprovedSubSharding( HloSharding sharding, HloInstruction* instruction, const ShapeIndex& index, bool may_combine_partial_sharding, bool allow_aggressive_resharding = false) { if (instruction->has_sharding()) { const HloSharding to_improved = instruction->sharding().GetSubSharding(instruction->shape(), index); return hlo_sharding_util::ReturnImprovedShardingImpl( std::move(sharding), &to_improved, ShapeUtil::GetSubshape(instruction->shape(), index), may_combine_partial_sharding, allow_aggressive_resharding); } else { return hlo_sharding_util::ReturnImprovedShardingImpl( std::move(sharding), nullptr, ShapeUtil::GetSubshape(instruction->shape(), index), may_combine_partial_sharding, allow_aggressive_resharding); } } bool MaybeImproveInstructionSharding(HloSharding sharding, HloInstruction* instruction, bool may_combine_partial_sharding, bool allow_aggressive_resharding = false) { if (auto new_sharding = ReturnImprovedSharding( std::move(sharding), instruction, may_combine_partial_sharding, allow_aggressive_resharding)) { instruction->set_sharding(std::move(*new_sharding)); return true; } return false; } bool MaybeImproveInstructionSubSharding( HloSharding sharding, HloInstruction* instruction, const ShapeIndex& index, bool may_combine_partial_sharding, bool allow_aggressive_resharding = false) { if (instruction->shape().IsTuple()) { if (auto new_sub_sharding = ReturnImprovedSubSharding( std::move(sharding), instruction, index, may_combine_partial_sharding, allow_aggressive_resharding)) { HloSharding new_sharding = instruction->has_sharding() ? instruction->sharding() : HloSharding::Single(instruction->shape(), HloSharding::Replicate()); ShapeTree<HloSharding> sharding_shape_tree = new_sharding.GetAsShapeTree(instruction->shape()); *sharding_shape_tree.mutable_element(index) = new_sub_sharding.value(); instruction->set_sharding(HloSharding::Tuple(sharding_shape_tree)); return true; } else { return false; } } CHECK(index.size() == 1 && index[0] == 0); return MaybeImproveInstructionSharding(std::move(sharding), instruction, may_combine_partial_sharding, allow_aggressive_resharding); } bool IsConvolutionKernelSmall(const HloInstruction* instruction) { CHECK_EQ(instruction->opcode(), HloOpcode::kConvolution); const HloInstruction* rhs = instruction->operand(1); const auto& dnums = instruction->convolution_dimension_numbers(); int64_t kernel_dim_prod = 1; int64_t output_dim_prod = 1; for (int64_t i = 0; i < dnums.input_spatial_dimensions().size(); ++i) { int64_t kernel_dim = rhs->shape().dimensions(dnums.kernel_spatial_dimensions(i)); kernel_dim_prod *= kernel_dim; int64_t output_dim = instruction->shape().dimensions(dnums.output_spatial_dimensions(i)); output_dim_prod *= output_dim; if (kernel_dim >= output_dim && (i < 2 || kernel_dim > 3 || kernel_dim_prod >= output_dim_prod)) { return false; } } return true; } bool IsPassthroughCustomOps(const HloInstruction* hlo) { if (hlo->IsCustomCall({"Sharding", "X64Combine", "LayoutConstraint"})) { return true; } if (hlo->operand_count() != 1 || !hlo->shape().IsArray() || !hlo->operand(0)->shape().IsArray() || hlo->operand(0)->shape().rank() != hlo->shape().rank()) { return false; } return hlo->IsCustomCall( {"ResizeNearest", "ResizeBilinear", "ResizeNearestGrad", "ResizeBilinearGrad", "Cholesky", host_memory_offload_annotations::kMoveToDeviceCustomCallTarget, host_memory_offload_annotations::kMoveToHostCustomCallTarget}); } const HloInstruction* PickRepresentativeOperand( const HloInstruction* instruction) { switch (instruction->opcode()) { case HloOpcode::kMap: case HloOpcode::kPad: case HloOpcode::kPower: case HloOpcode::kOptimizationBarrier: case HloOpcode::kReverse: case HloOpcode::kSlice: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: // For these opcodes the output sharding has to be determined by the // sharding of the first operand but we can only determine sharding based // on it if it already has a sharding. if (instruction->operand(0)->has_sharding()) { return instruction->operand(0); } return nullptr; case HloOpcode::kAbs: case HloOpcode::kAdd: case HloOpcode::kAnd: case HloOpcode::kAtan2: case HloOpcode::kBitcastConvert: case HloOpcode::kCeil: case HloOpcode::kClamp: case HloOpcode::kClz: case HloOpcode::kCompare: case HloOpcode::kComplex: case HloOpcode::kConcatenate: case HloOpcode::kConvert: case HloOpcode::kCopy: case HloOpcode::kCos: case HloOpcode::kAllGather: case HloOpcode::kAllReduce: case HloOpcode::kReduceScatter: case HloOpcode::kAllToAll: case HloOpcode::kCollectiveBroadcast: case HloOpcode::kCollectivePermute: case HloOpcode::kDivide: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kFloor: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kMultiply: case HloOpcode::kNegate: case HloOpcode::kNot: case HloOpcode::kOr: case HloOpcode::kPopulationCount: case HloOpcode::kReal: case HloOpcode::kReducePrecision: case HloOpcode::kRemainder: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kRsqrt: case HloOpcode::kSelect: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kTopK: case HloOpcode::kSort: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kSubtract: case HloOpcode::kStochasticConvert: case HloOpcode::kTan: case HloOpcode::kTanh: case HloOpcode::kWhile: case HloOpcode::kXor: { // For these opcodes the output sharding can be determined by any operand // so we find the operand with the most specific sharding. const HloInstruction* best_operand = nullptr; for (const HloInstruction* operand : instruction->operands()) { if (operand->has_sharding() && (best_operand == nullptr || hlo_sharding_util::IsShardingMoreSpecific( operand->sharding(), best_operand->sharding()))) { best_operand = operand; } } return best_operand; } case HloOpcode::kCustomCall: { if (IsPassthroughCustomOps(instruction)) { return instruction->operand(0); } return nullptr; } // There is no suitable operand for the rest of the opcodes. case HloOpcode::kAddDependency: case HloOpcode::kAfterAll: case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: case HloOpcode::kAllGatherStart: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduceStart: case HloOpcode::kAllReduceDone: case HloOpcode::kBatchNormGrad: case HloOpcode::kBatchNormInference: case HloOpcode::kBatchNormTraining: case HloOpcode::kBitcast: case HloOpcode::kBroadcast: case HloOpcode::kCall: case HloOpcode::kCholesky: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCollectivePermuteStart: case HloOpcode::kConditional: case HloOpcode::kConstant: case HloOpcode::kConvolution: case HloOpcode::kCopyDone: case HloOpcode::kCopyStart: case HloOpcode::kDomain: case HloOpcode::kDot: case HloOpcode::kDynamicSlice: case HloOpcode::kDynamicUpdateSlice: case HloOpcode::kDynamicReshape: case HloOpcode::kFft: case HloOpcode::kFusion: case HloOpcode::kGather: case HloOpcode::kGetTupleElement: case HloOpcode::kInfeed: case HloOpcode::kIota: case HloOpcode::kOutfeed: case HloOpcode::kParameter: case HloOpcode::kPartitionId: case HloOpcode::kRecv: case HloOpcode::kRecvDone: case HloOpcode::kReduce: case HloOpcode::kReduceWindow: case HloOpcode::kReplicaId: case HloOpcode::kReshape: case HloOpcode::kRng: case HloOpcode::kRngGetAndUpdateState: case HloOpcode::kRngBitGenerator: case HloOpcode::kScatter: case HloOpcode::kSelectAndScatter: case HloOpcode::kSend: case HloOpcode::kSendDone: case HloOpcode::kTranspose: case HloOpcode::kTriangularSolve: case HloOpcode::kTuple: case HloOpcode::kGetDimensionSize: case HloOpcode::kSetDimensionSize: return nullptr; } } bool SupportSpatialPartitioning( const HloInstruction* instruction, const ShardingPropagation::ComputationMap& computation_map, bool is_spmd, bool allow_spmd_sharding_propagation_to_output, bool allow_spmd_sharding_propagation_to_parameters, const CustomCallShardingHelper* sharding_helper) { const bool is_entry_root = instruction->parent() ->parent() ->entry_computation() ->root_instruction() == instruction; if (instruction->parent()->root_instruction() == instruction && computation_map.find(instruction->parent()) == computation_map.end() && !(is_entry_root && allow_spmd_sharding_propagation_to_output)) { // We don't support sharding the root instruction of a computation yet, // unless the computation is a while body. return false; } if (instruction->IsElementwise() && (instruction->opcode() != HloOpcode::kRng || is_spmd)) { return true; } switch (instruction->opcode()) { case HloOpcode::kBroadcast: case HloOpcode::kConcatenate: case HloOpcode::kConditional: case HloOpcode::kConstant: case HloOpcode::kConvolution: case HloOpcode::kOptimizationBarrier: case HloOpcode::kDot: case HloOpcode::kDynamicSlice: case HloOpcode::kDynamicUpdateSlice: case HloOpcode::kGather: case HloOpcode::kGetTupleElement: case HloOpcode::kInfeed: case HloOpcode::kIota: case HloOpcode::kPad: case HloOpcode::kReduceWindow: case HloOpcode::kReshape: case HloOpcode::kScatter: case HloOpcode::kSelectAndScatter: case HloOpcode::kSlice: case HloOpcode::kSort: case HloOpcode::kTranspose: case HloOpcode::kTuple: case HloOpcode::kWhile: case HloOpcode::kReduce: case HloOpcode::kRngBitGenerator: case HloOpcode::kAllReduce: case HloOpcode::kReduceScatter: return true; case HloOpcode::kParameter: return allow_spmd_sharding_propagation_to_parameters || computation_map.find(instruction->parent()) != computation_map.end(); case HloOpcode::kReverse: return is_spmd; case HloOpcode::kCustomCall: if (!is_spmd) { return false; } if (auto* partitioner = GetCustomCallPartitioner(instruction->custom_call_target())) { return partitioner->IsCustomCallShardable(instruction); } return (IsPassthroughCustomOps(instruction) || sharding_helper->IsCustomCallShardable(instruction)); default: return false; } } std::optional<HloSharding> LookaheadUserSharding(HloInstruction* instr, bool is_spmd, const CallGraph& call_graph) { if (instr->user_count() != 1) { return std::nullopt; } HloInstruction* current_user = instr->users()[0]; std::optional<HloSharding> sharding; std::vector<HloInstruction*> users_chain = {instr, current_user}; // Collect single user instructions along the way. while (!current_user->has_sharding()) { // Only consider single user chains. if (current_user->users().size() != 1) { users_chain.clear(); break; } current_user = current_user->users()[0]; users_chain.push_back(current_user); } // Early exit for unsupported cases. if (users_chain.empty()) { return std::nullopt; } for (int i = users_chain.size() - 1; i >= 1; --i) { HloInstruction* user = users_chain[i]; HloInstruction* current = users_chain[i - 1]; CHECK(user->has_sharding()); sharding = ShardingPropagation::GetShardingFromUser( *current, *user, INT64_MAX, is_spmd, call_graph, /*sharding_helper=*/nullptr); // We need to set the sharding to the instruction, because // GetShardingFromUser() interface uses sharding from the instruction // itself. It will be cleared out later. if (sharding.has_value() && i != 1) { current->set_sharding(*sharding); continue; } break; } // Clear the sharding of the middle instructions we set the sharding of // because they were unsharded. for (int i = 1; i < users_chain.size() - 1; ++i) { users_chain[i]->clear_sharding(); } return sharding; } bool InferGatherParallelShardingFromOperands( HloInstruction* instruction, const hlo_sharding_util::GatherScatterParallelDims& parallel_dims, bool may_combine_partial_sharding) { CHECK(DynCast<HloGatherInstruction>(instruction)); bool changed = false; auto aligned_operand_parallel_dims = hlo_sharding_util::IndexAlignedOperandParallelDims(parallel_dims); auto output_parallel_dims = hlo_sharding_util::GetGatherParallelOutputDims( *instruction, parallel_dims); // Infer output sharding from scatter operand sharding. if (hlo_sharding_util::IsSpatiallyPartitioned(instruction->operand(0))) { changed |= MaybeImproveInstructionSharding( hlo_sharding_util:: InferGatherScatterParallelShardingFromOperandSharding( instruction->operand(0)->sharding(), instruction->operand(0)->shape(), instruction->shape(), absl::MakeConstSpan(aligned_operand_parallel_dims), absl::MakeConstSpan(output_parallel_dims)), instruction, may_combine_partial_sharding); } // Infer output sharding from scatter indices sharding. if (hlo_sharding_util::IsSpatiallyPartitioned(instruction->operand(1))) { changed |= MaybeImproveInstructionSharding( hlo_sharding_util:: InferGatherScatterParallelShardingFromOperandSharding( instruction->operand(1)->sharding(), instruction->operand(1)->shape(), instruction->shape(), absl::MakeConstSpan(parallel_dims.indices_parallel_dims), absl::MakeConstSpan(output_parallel_dims)), instruction, may_combine_partial_sharding); } return changed; } bool InferScatterParallelShardingFromOperands( HloInstruction* instruction, const hlo_sharding_util::GatherScatterParallelDims& parallel_dims, bool may_combine_partial_sharding) { HloScatterInstruction* scatter = DynCast<HloScatterInstruction>(instruction); CHECK(scatter); const int64_t operand_count = scatter->scatter_operand_count(); auto scatter_operands = scatter->scatter_operands(); auto scatter_indices = scatter->scatter_indices(); auto scatter_updates = scatter->scatter_updates(); bool changed = false; auto aligned_operand_parallel_dims = hlo_sharding_util::IndexAlignedOperandParallelDims(parallel_dims); auto update_parallel_dims = hlo_sharding_util::GetScatterParallelUpdateDims( *instruction, parallel_dims); auto output_parallel_dims = aligned_operand_parallel_dims; // Infer output sharding from scatter operand sharding. Shape shape = operand_count == 1 ? instruction->shape() : ShapeUtil::GetSubshape(instruction->shape(), {0}); for (int64_t i = 0; i != operand_count; ++i) { if (hlo_sharding_util::IsSpatiallyPartitioned(scatter_operands[i])) { changed |= MaybeImproveInstructionSubSharding( hlo_sharding_util:: InferGatherScatterParallelShardingFromOperandSharding( scatter_operands[i]->sharding(), scatter_operands[i]->shape(), shape, absl::MakeConstSpan(aligned_operand_parallel_dims), absl::MakeConstSpan(output_parallel_dims)), instruction, {i}, may_combine_partial_sharding); } } // Infer output sharding from scatter indices sharding. if (hlo_sharding_util::IsSpatiallyPartitioned(scatter_indices)) { auto parallel_sharding_from_indices = hlo_sharding_util:: InferGatherScatterParallelShardingFromOperandSharding( scatter_indices->sharding(), scatter_indices->shape(), shape, absl::MakeConstSpan(parallel_dims.indices_parallel_dims), absl::MakeConstSpan(output_parallel_dims)); for (int64_t i = 0; i != operand_count; ++i) { changed |= MaybeImproveInstructionSubSharding( parallel_sharding_from_indices, instruction, {i}, may_combine_partial_sharding); } } // Infer output sharding from scatter update sharding. for (int64_t i = 0; i != operand_count; ++i) { if (hlo_sharding_util::IsSpatiallyPartitioned(scatter_updates[i])) { changed |= MaybeImproveInstructionSubSharding( hlo_sharding_util:: InferGatherScatterParallelShardingFromOperandSharding( scatter_updates[i]->sharding(), scatter_updates[i]->shape(), shape, absl::MakeConstSpan(update_parallel_dims), absl::MakeConstSpan(output_parallel_dims)), instruction, {i}, may_combine_partial_sharding); } } return changed; } bool CanPropagateThroughAtAggressiveLevel(const HloInstruction& inst, int64_t aggressiveness) { // At minimum aggressiveness, only allow pass-through ops. if (aggressiveness < 1 && !(inst.IsElementwise() || inst.IsCustomCall("Sharding")) && inst.opcode() != HloOpcode::kTranspose && inst.opcode() != HloOpcode::kReshape && inst.opcode() != HloOpcode::kTuple && inst.opcode() != HloOpcode::kGetTupleElement && inst.opcode() != HloOpcode::kWhile && inst.opcode() != HloOpcode::kDynamicSlice && inst.opcode() != HloOpcode::kDynamicUpdateSlice && inst.opcode() != HloOpcode::kOptimizationBarrier && inst.opcode() != HloOpcode::kConcatenate && inst.opcode() != HloOpcode::kCall && inst.opcode() != HloOpcode::kCopy) { return false; } // Broadcast propagation should have at least aggressiveness 2. if (aggressiveness < 2 && inst.opcode() == HloOpcode::kBroadcast) { return false; } return true; } bool SameShardingMetadata(const HloSharding& a, const HloSharding& b) { DCHECK_EQ(a, b); auto same_metadata = [](absl::Span<const OpMetadata> a, absl::Span<const OpMetadata> b) { if (a.size() != b.size()) return false; for (int i = 0, e = a.size(); i < e; ++i) { if (!protobuf_util::ProtobufEquals(a[i], b[i])) { return false; } } return true; }; if (a.IsTuple()) { for (int i = 0, e = a.tuple_elements().size(); i < e; ++i) { if (!same_metadata(a.tuple_elements()[i].metadata(), b.tuple_elements()[i].metadata())) { return false; } } return true; } else { return same_metadata(a.metadata(), b.metadata()); } } auto same_metadata = [](absl::Span<const OpMetadata> a, absl::Span<const OpMetadata> b) { if (a.size() != b.size()) return false; for (int i = 0, e = a.size(); i < e; ++i) { if (!protobuf_util::ProtobufEquals(a[i], b[i])) { return false; } } return true; }; bool AssignShardingMetadata( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { bool changed = false; for (HloComputation* computation : module->computations(execution_threads)) { for (HloInstruction* instruction : computation->instructions()) { const auto& metadata = instruction->metadata(); if (!instruction->has_sharding() || metadata.ByteSizeLong() == 0) { continue; } HloSharding sharding_with_metadata = instruction->sharding().WithMetadata({metadata}, /*overwrite=*/false); if (!SameShardingMetadata(instruction->sharding(), sharding_with_metadata)) { instruction->set_sharding(std::move(sharding_with_metadata)); changed = true; } } } return changed; } bool RemoveShardingMetadata( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { bool changed = false; for (HloComputation* computation : module->computations(execution_threads)) { for (HloInstruction* instruction : computation->instructions()) { if (!instruction->has_sharding()) { continue; } HloSharding sharding_no_metadata = instruction->sharding().WithoutMetadata(); if (!SameShardingMetadata(instruction->sharding(), sharding_no_metadata)) { instruction->set_sharding(std::move(sharding_no_metadata)); changed = true; } } } return changed; } absl::Status CheckAndUpdateDeviceAssignmentsInWhileBody( HloInstruction* while_instruction) { auto bad_status = [](HloInstruction* instruction, int64_t device, HloInstruction* channel_instruction, int64_t correct_device) { return FailedPrecondition( "Instruction: %s is on device: %d, which conflicts with device: %d " "of channel instruction: %s", instruction->name(), device, correct_device, channel_instruction->name()); }; CHECK_EQ(while_instruction->opcode(), HloOpcode::kWhile); HloComputation* while_body = while_instruction->while_body(); // Maps a device number to an instruction in the while_body with that // device assignment. std::map<int64_t, HloInstruction*> devices_to_instructions; std::optional<int64_t> unique_device = std::nullopt; HloInstruction* channel_instruction = nullptr; for (HloInstruction* instruction : while_body->instructions()) { if (instruction->sharding_unique_device()) { auto opcode = instruction->opcode(); int64_t device = *instruction->sharding_unique_device(); if (unique_device.has_value()) { if (*unique_device != device) { return bad_status(instruction, device, channel_instruction, *unique_device); } } else if (((opcode == HloOpcode::kSend || opcode == HloOpcode::kRecv) && !Cast<HloSendRecvInstruction>(instruction) ->is_host_transfer()) // Cross-replica AllReduces don't have a channel_id, and we // don't enforce any invariant about their device assignment. || ((opcode == HloOpcode::kAllReduce || opcode == HloOpcode::kReduceScatter) && instruction->channel_id())) { channel_instruction = instruction; unique_device = device; if (!devices_to_instructions.empty()) { for (auto it = devices_to_instructions.begin(); it != devices_to_instructions.end(); ++it) { if (*unique_device != it->first) { return bad_status(it->second, it->first, channel_instruction, *unique_device); } } } } else { devices_to_instructions[device] = instruction; } } } if (unique_device.has_value()) { auto while_device = while_instruction->sharding_unique_device(); if (while_device.has_value() && *unique_device != *while_device) { return bad_status(while_instruction, *while_device, channel_instruction, *unique_device); } auto body_root = while_body->root_instruction(); auto root_device = body_root->sharding_unique_device(); if (!root_device.has_value()) { body_root->set_device_sharding(*unique_device); } else if (*unique_device != *root_device) { return bad_status(body_root, *root_device, channel_instruction, *unique_device); } } return absl::OkStatus(); } auto bad_status = [](HloInstruction* instruction, int64_t device, HloInstruction* channel_instruction, int64_t correct_device) { return FailedPrecondition( "Instruction: %s is on device: %d, which conflicts with device: %d " "of channel instruction: %s", instruction->name(), device, correct_device, channel_instruction->name()); }; bool RefineManualAutoShardingFromAuto( const HloSharding& to_merge, absl::Span<const int64_t> unspecified_dims, HloSharding* auto_sharding, HloSharding* manual_sharding) { if (!manual_sharding->IsManualSubgroup() || auto_sharding->IsManualSubgroup() || !manual_sharding->HasPartialReplication() || manual_sharding->subgroup_types().size() != 2) { // We do not support nested subgroup manual. man_conversion_op must have // replication in order to be merged. return false; } HloSharding partial_rep = hlo_sharding_util::PartiallyReplicateTiledShardingOnAllDimsExcept( to_merge, unspecified_dims); if (partial_rep.IsTileMaximal()) { return false; } // Merge with the non-manual partial annotation. if (!hlo_sharding_util::MergeShardingIfCompatible( partial_rep, auto_sharding->NumTiles() + 1, auto_sharding)) { return false; } // Merge with the manual partial annotation. const int64_t data_rank = partial_rep.TiledDataRank(); // We are also merging the non-manual sharding into the manual sharding. To // leverage existing merging implementation, we treat the manual dim as a // data dim, and add it right before the replication dim. std::vector<int64_t> partial_manual_shape( partial_rep.tile_assignment().dimensions().begin(), partial_rep.tile_assignment().dimensions().end()); partial_manual_shape.insert(partial_manual_shape.begin() + data_rank, 1); auto partial_tiling_for_manual = partial_rep.tile_assignment().Reshape(partial_manual_shape); HloSharding partial_rep_for_manual = HloSharding::PartialTile( partial_tiling_for_manual, partial_rep.metadata()); auto man_tiling = manual_sharding->tile_assignment(); if (manual_sharding->subgroup_types().back() != OpSharding::REPLICATED) { // Move the manual dim before replication dim. std::vector<int> transposed_dims(man_tiling.num_dimensions()); absl::c_iota(transposed_dims, 0); std::swap(transposed_dims.back(), transposed_dims[data_rank]); man_tiling = man_tiling.Transpose(transposed_dims); } HloSharding tmp_sharding_for_merging = HloSharding::PartialTile( std::move(man_tiling), manual_sharding->metadata()); if (!hlo_sharding_util::MergeShardingIfCompatible( partial_rep_for_manual, tmp_sharding_for_merging.NumTiles() + 1, &tmp_sharding_for_merging)) { return false; } std::vector<OpSharding::Type> subgroup_types; subgroup_types.push_back(OpSharding::MANUAL); if (tmp_sharding_for_merging.HasPartialReplication()) { subgroup_types.push_back(OpSharding::REPLICATED); } *manual_sharding = HloSharding::Subgroup( tmp_sharding_for_merging.tile_assignment(), subgroup_types, tmp_sharding_for_merging.metadata()); return true; } bool RefineManualAutoShardingFromManual( const HloSharding& to_merge, absl::Span<const int64_t> unspecified_dims, HloSharding* auto_sharding, HloSharding* manual_sharding) { if (!to_merge.IsManualSubgroup() || !manual_sharding->IsManualSubgroup() || !manual_sharding->HasPartialReplication() || auto_sharding->IsManualSubgroup() || manual_sharding->subgroup_types().size() != 2) { return false; } HloSharding partial_rep = hlo_sharding_util::PartiallyReplicateTiledShardingOnAllDimsExcept( to_merge, unspecified_dims); if (partial_rep.IsTileMaximal()) { return false; } if (!hlo_sharding_util::MergeShardingIfCompatible( partial_rep, manual_sharding->NumTiles() + 1, manual_sharding)) { return false; } HloSharding partial_rep_for_auto = HloSharding::Subgroup( partial_rep.tile_assignment(), std::vector<OpSharding::Type>(partial_rep.subgroup_types().size(), OpSharding::REPLICATED), partial_rep.metadata()); if (!hlo_sharding_util::MergeShardingIfCompatible( partial_rep_for_auto, auto_sharding->NumTiles() + 1, auto_sharding)) { return false; } return true; } bool InferUnspecifiedDimsFromOperand(HloInstruction* annotate_op, absl::Span<const int64_t> unspecified_dims, HloInstruction** man_conversion_op_after) { // ProcessShardingInstruction will either keep the "Sharding" custom call as // is or replace it with a copy. CHECK(annotate_op->IsCustomCall("Sharding") || annotate_op->opcode() == HloOpcode::kCopy); if (!hlo_sharding_util::IsSpatiallyPartitioned(annotate_op->operand(0))) { return false; } const HloSharding& operand_sharding = annotate_op->operand(0)->sharding(); if (!operand_sharding.IsTiled()) { return false; } HloInstruction* man_conversion_op = nullptr; if (annotate_op->user_count() == 1) { HloInstruction* user = annotate_op->users()[0]; if (user->IsCustomCall("SPMDFullToShardShape") || user->IsCustomCall("SPMDShardToFullShape")) { std::vector<int64_t> user_unspec_dims; if (!sharding_op_util::ParseAttributes( Cast<HloCustomCallInstruction>(user)->opaque(), &user_unspec_dims) .ok()) { return false; } absl::c_sort(user_unspec_dims); if (unspecified_dims != user_unspec_dims) { // The manual/auto conversion op must have the same set of unspecified // dims. return false; } man_conversion_op = user; } } *man_conversion_op_after = man_conversion_op; if (man_conversion_op == nullptr) { HloSharding partial_replicated = hlo_sharding_util::PartiallyReplicateTiledShardingOnAllDimsExcept( operand_sharding, unspecified_dims); HloSharding sharding = annotate_op->sharding(); if (!hlo_sharding_util::MergeShardingIfCompatible( partial_replicated, sharding.NumTiles() + 1, &sharding)) { return false; } annotate_op->set_sharding(sharding); return true; } if (man_conversion_op->IsCustomCall("SPMDFullToShardShape")) { HloSharding auto_sharding = annotate_op->sharding(); HloSharding manual_sharding = man_conversion_op->sharding(); if (!RefineManualAutoShardingFromAuto(operand_sharding, unspecified_dims, &auto_sharding, &manual_sharding)) { return false; } annotate_op->set_sharding(auto_sharding); man_conversion_op->set_sharding(manual_sharding); return true; } CHECK(man_conversion_op->IsCustomCall("SPMDShardToFullShape")); HloSharding manual_sharding = annotate_op->sharding(); HloSharding auto_sharding = man_conversion_op->sharding(); if (!RefineManualAutoShardingFromManual(operand_sharding, unspecified_dims, &auto_sharding, &manual_sharding)) { return false; } annotate_op->set_sharding(manual_sharding); man_conversion_op->set_sharding(auto_sharding); return true; } bool InferUnspecifiedDimsFromOneUser(HloInstruction* annotate_op, const HloInstruction* user, int64_t aggressiveness, bool is_spmd, absl::Span<const int64_t> unspecified_dims, HloInstruction* man_conversion_op, const CallGraph& call_graph) { CHECK(annotate_op->IsCustomCall("Sharding") || annotate_op->opcode() == HloOpcode::kCopy); if (!user->has_sharding() || !user->sharding().IsTiled()) { return false; } std::optional<HloSharding> user_sharding = ShardingPropagation::GetShardingFromUser( man_conversion_op == nullptr ? *annotate_op : *man_conversion_op, *user, aggressiveness, is_spmd, call_graph, /*sharding_helper=*/nullptr); if (!user_sharding.has_value() || user_sharding->IsTileMaximal()) { return false; } if (man_conversion_op == nullptr) { HloSharding partial_replicated = hlo_sharding_util::PartiallyReplicateTiledShardingOnAllDimsExcept( *user_sharding, unspecified_dims); HloSharding sharding = annotate_op->sharding(); if (!hlo_sharding_util::MergeShardingIfCompatible( partial_replicated, sharding.NumTiles() + 1, &sharding)) { return false; } annotate_op->set_sharding(sharding); return true; } if (man_conversion_op->IsCustomCall("SPMDFullToShardShape")) { HloSharding auto_sharding = annotate_op->sharding(); HloSharding manual_sharding = man_conversion_op->sharding(); if (!RefineManualAutoShardingFromManual(*user_sharding, unspecified_dims, &auto_sharding, &manual_sharding)) { return false; } annotate_op->set_sharding(auto_sharding); man_conversion_op->set_sharding(manual_sharding); return true; } CHECK(man_conversion_op->IsCustomCall("SPMDShardToFullShape")); HloSharding manual_sharding = annotate_op->sharding(); HloSharding auto_sharding = man_conversion_op->sharding(); if (!RefineManualAutoShardingFromAuto(*user_sharding, unspecified_dims, &auto_sharding, &manual_sharding)) { return false; } annotate_op->set_sharding(manual_sharding); man_conversion_op->set_sharding(auto_sharding); return true; } bool InferUnspecifiedDimsFromUsers(HloInstruction* annotate_op, absl::Span<const int64_t> unspecified_dims, int64_t aggressiveness, bool is_spmd, HloInstruction** man_conversion_op_after, const CallGraph& call_graph) { HloInstruction* man_conversion_op = nullptr; if (annotate_op->user_count() == 1) { HloInstruction* user = annotate_op->users()[0]; if (user->IsCustomCall("SPMDFullToShardShape") || user->IsCustomCall("SPMDShardToFullShape")) { std::vector<int64_t> user_unspec_dims; absl::c_sort(user_unspec_dims); if (!sharding_op_util::ParseAttributes( Cast<HloCustomCallInstruction>(user)->opaque(), &user_unspec_dims) .ok() || unspecified_dims != user_unspec_dims) { // The manual/auto conversion op must have the same set of unspecified // dims. return false; } man_conversion_op = user; } } *man_conversion_op_after = man_conversion_op; HloInstruction* op_for_users = man_conversion_op == nullptr ? annotate_op : man_conversion_op; bool changed = false; for (HloInstruction* user : op_for_users->users()) { changed |= InferUnspecifiedDimsFromOneUser( annotate_op, user, aggressiveness, is_spmd, unspecified_dims, man_conversion_op, call_graph); } return changed; } bool InferUnspecifiedDimsFromShardGroup( HloInstruction* annotate_op, absl::Span<const int64_t> unspecified_dims, const absl::flat_hash_set<HloInstruction*>& shard_group) { // ProcessShardingInstruction will either keep the "Sharding" custom call as // is or replace it with a copy. CHECK(annotate_op->IsCustomCall("Sharding") || annotate_op->opcode() == HloOpcode::kCopy); // Do not propagate sharding to ShardBarrierTo custom-call. if (annotate_op->IsCustomCall(spmd::kShardBarrierTo)) { return false; } bool changed = false; for (const HloInstruction* member : shard_group) { if (member == annotate_op) { continue; } // Do not propagate sharding from ShardBarrierFrom custom-call. if (member->IsCustomCall(spmd::kShardBarrierFrom)) { continue; } if (!hlo_sharding_util::IsSpatiallyPartitioned(member)) { continue; } const HloSharding& member_sharding = member->sharding(); if (!member_sharding.IsTiled()) { continue; } HloSharding partial_replicated = hlo_sharding_util::PartiallyReplicateTiledShardingOnAllDimsExcept( member_sharding, unspecified_dims); HloSharding sharding = annotate_op->sharding(); if (!hlo_sharding_util::MergeShardingIfCompatible( partial_replicated, sharding.NumTiles() + 1, &sharding)) { continue; } annotate_op->set_sharding(sharding); changed |= true; } return changed; } bool IsCSEPreventionTarget(const HloInstruction* instruction) { // Scalar broadcasts are the most common CSE target that causes cross-layer // propagation on unrelated subgraphs. return instruction->opcode() == HloOpcode::kBroadcast && instruction->operand(0)->shape().rank() == 0; } HloSharding SetCSEPreventionSharding(const HloSharding& sharding) { OpMetadata metadata; metadata.set_op_name("_sharding_propagation_cse_prevention"); return sharding.WithMetadata({metadata}, /*overwrite=*/true); } bool IsCSEPreventionSharding(const HloSharding& sharding) { if (sharding.metadata().size() != 1) { return false; } return sharding.metadata()[0].op_name() == "_sharding_propagation_cse_prevention"; } bool InferDotShardingFromOperands( HloInstruction* instruction, const CallGraph& call_graph, const dot_as_convolution_util::DotConvolutionDimsInfo& dnums, bool may_combine_partial_sharding, bool is_spmd) { auto from_operand = [&](int64_t operand_index) { auto operand = instruction->operand(operand_index); const HloSharding& operand_sharding = operand->sharding(); if (operand_sharding.IsTileMaximal()) { return operand_sharding; } std::vector<int64_t> contracting_dims; contracting_dims.reserve(dnums.contracting_dims.size()); for (const auto& dim : dnums.contracting_dims) { contracting_dims.push_back(operand_index == 0 ? dim.lhs : dim.rhs); } // It's possible that some size-1 spatial dims of convolutions are parsed as // non-contracting dims. We might have tiled dimensions on them. for (const auto& dim : operand_index == 0 ? dnums.rhs_non_contracting_dims : dnums.lhs_non_contracting_dims) { int64_t d = operand_index == 0 ? dim.lhs : dim.rhs; if (d >= 0) { contracting_dims.push_back(d); } } auto replicate_contracting_dims = hlo_sharding_util::PartiallyReplicateTiledShardingOnDims( operand_sharding, contracting_dims); std::vector<int64_t> out_dims_to_op_perm(instruction->shape().rank(), -1); std::vector<int64_t> op_dims_to_output_perm(operand->shape().rank(), -1); for (const auto& dim : dnums.batch_dims) { out_dims_to_op_perm[dim.output] = operand_index == 0 ? dim.lhs : dim.rhs; op_dims_to_output_perm[operand_index == 0 ? dim.lhs : dim.rhs] = dim.output; } for (const auto& dim : operand_index == 0 ? dnums.lhs_non_contracting_dims : dnums.rhs_non_contracting_dims) { out_dims_to_op_perm[dim.output] = operand_index == 0 ? dim.lhs : dim.rhs; op_dims_to_output_perm[operand_index == 0 ? dim.lhs : dim.rhs] = dim.output; } return *hlo_sharding_util::TransposeShardingWithCollapsedDims( replicate_contracting_dims, op_dims_to_output_perm, out_dims_to_op_perm); }; std::optional<HloSharding> improved_operand_0; std::optional<HloSharding> improved_operand_1; if (hlo_sharding_util::IsSpatiallyPartitioned(instruction->operand(0))) { improved_operand_0 = ReturnImprovedSharding( from_operand(0), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/false); } if (hlo_sharding_util::IsSpatiallyPartitioned(instruction->operand(1))) { improved_operand_1 = ReturnImprovedSharding( from_operand(1), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/false); } // If not improved sharding found then do not set any sharding. if (!improved_operand_0.has_value() && !improved_operand_1.has_value()) { return false; } // Sharding found from operand 0 but not operand 1. Set sharding from operand // 0 if (improved_operand_0.has_value() && !improved_operand_1.has_value()) { instruction->set_sharding(*improved_operand_0); return true; } // Sharding found from operand 1 but not operand 0. Set sharding from operand // 1 if (!improved_operand_0.has_value() && improved_operand_1.has_value()) { instruction->set_sharding(*improved_operand_1); return true; } CHECK(improved_operand_0.has_value() && improved_operand_1.has_value()); std::optional<HloSharding> lookahead_sharding = LookaheadUserSharding(instruction, is_spmd, call_graph); std::array<HloSharding, 2> sharding_priority = {*improved_operand_0, *improved_operand_1}; bool priority_defined_with_lookahead = false; // Found sharding from lookahead. if (lookahead_sharding.has_value()) { const bool operand_0_is_lookahead_subtiling = hlo_sharding_util::IsSubTilingOrEqualSharding( instruction->shape(), *lookahead_sharding, *improved_operand_0); const bool operand_1_is_lookahead_subtiling = hlo_sharding_util::IsSubTilingOrEqualSharding( instruction->shape(), *lookahead_sharding, *improved_operand_1); // If the sharding from operand 0 is a subtiling of the user, but not the // one from operand 1 prioritize that sharding. if (operand_0_is_lookahead_subtiling && !operand_1_is_lookahead_subtiling) { priority_defined_with_lookahead = true; } // If the sharding from operand 1 is a subtiling of the user, but not the // one from operand 0 prioritize that sharding. if (!operand_0_is_lookahead_subtiling && operand_1_is_lookahead_subtiling) { instruction->set_sharding(*improved_operand_1); std::swap(sharding_priority[0], sharding_priority[1]); priority_defined_with_lookahead = true; } } // If lookahead didn't define a priority then use size. if (!priority_defined_with_lookahead && ShapeUtil::ByteSizeOf(instruction->operand(0)->shape()) < ShapeUtil::ByteSizeOf(instruction->operand(1)->shape())) { std::swap(sharding_priority[0], sharding_priority[1]); } // Set primary sharding to the instruction and then try to improve it with // the secondary sharding. instruction->set_sharding(sharding_priority[0]); MaybeImproveInstructionSharding(sharding_priority[1], instruction, may_combine_partial_sharding); return true; } auto from_operand = [&](int64_t operand_index) { auto operand = instruction->operand(operand_index); const HloSharding& operand_sharding = operand->sharding(); if (operand_sharding.IsTileMaximal()) { return operand_sharding; } std::vector<int64_t> contracting_dims; contracting_dims.reserve(dnums.contracting_dims.size()); for (const auto& dim : dnums.contracting_dims) { contracting_dims.push_back(operand_index == 0 ? dim.lhs : dim.rhs); } // It's possible that some size-1 spatial dims of convolutions are parsed as // non-contracting dims. We might have tiled dimensions on them. for (const auto& dim : operand_index == 0 ? dnums.rhs_non_contracting_dims : dnums.lhs_non_contracting_dims) { int64_t d = operand_index == 0 ? dim.lhs : dim.rhs; if (d >= 0) { contracting_dims.push_back(d); } } auto replicate_contracting_dims = hlo_sharding_util::PartiallyReplicateTiledShardingOnDims( operand_sharding, contracting_dims); std::vector<int64_t> out_dims_to_op_perm(instruction->shape().rank(), -1); std::vector<int64_t> op_dims_to_output_perm(operand->shape().rank(), -1); for (const auto& dim : dnums.batch_dims) { out_dims_to_op_perm[dim.output] = operand_index == 0 ? dim.lhs : dim.rhs; op_dims_to_output_perm[operand_index == 0 ? dim.lhs : dim.rhs] = dim.output; } for (const auto& dim : operand_index == 0 ? dnums.lhs_non_contracting_dims : dnums.rhs_non_contracting_dims) { out_dims_to_op_perm[dim.output] = operand_index == 0 ? dim.lhs : dim.rhs; op_dims_to_output_perm[operand_index == 0 ? dim.lhs : dim.rhs] = dim.output; } return *hlo_sharding_util::TransposeShardingWithCollapsedDims( replicate_contracting_dims, op_dims_to_output_perm, out_dims_to_op_perm); }; bool InferConvolutionShardingFromOperands(HloInstruction* instruction, const CallGraph& call_graph, int64_t aggressiveness, bool may_combine_partial_sharding, bool is_spmd) { auto get_partitions_for_dims = [&](const HloInstruction* inst, absl::Span< const dot_as_convolution_util::DotConvolutionDimsInfo::DimNums> dims, int lhs_or_rhs) { int64_t partitions = 1; if (!inst->has_sharding()) { return partitions; } const auto& sharding = inst->sharding(); if (sharding.IsTileMaximal()) { return partitions; } for (const auto& dim : dims) { if (lhs_or_rhs == 0) { partitions *= sharding.tile_assignment().dim(dim.lhs); } else { CHECK_EQ(lhs_or_rhs, 1); partitions *= sharding.tile_assignment().dim(dim.rhs); } } return partitions; }; auto dot_dims = dot_as_convolution_util::ParseConvolutionDimsInfo(instruction); const int64_t lhs_conv_spatial_partitions = get_partitions_for_dims( instruction->operand(0), dot_dims.conv_spatial_dims, 0); const int64_t rhs_conv_spatial_partitions = get_partitions_for_dims( instruction->operand(1), dot_dims.conv_spatial_dims, 1); if (dot_dims.conv_spatial_dims.empty() || (lhs_conv_spatial_partitions == 1 && rhs_conv_spatial_partitions == 1 && instruction->batch_group_count() == 1 && instruction->feature_group_count() == 1)) { return InferDotShardingFromOperands(instruction, call_graph, dot_dims, may_combine_partial_sharding, is_spmd); } const auto& dnums = instruction->convolution_dimension_numbers(); const HloInstruction* lhs = instruction->operand(0); auto get_tiled_sharding_based_on_lhs = [&] { CHECK(!lhs->sharding().IsTileMaximal()); std::vector<int64_t> output_to_lhs_indices(instruction->shape().rank()); output_to_lhs_indices[dnums.output_batch_dimension()] = dnums.input_batch_dimension(); output_to_lhs_indices[dnums.output_feature_dimension()] = dnums.input_feature_dimension(); for (int64_t i = 0; i < dnums.input_spatial_dimensions_size(); ++i) { output_to_lhs_indices[dnums.output_spatial_dimensions(i)] = dnums.input_spatial_dimensions(i); } return hlo_sharding_util::TransposeSharding(lhs->sharding(), output_to_lhs_indices); }; if (!hlo_sharding_util::IsSpatiallyPartitioned(lhs)) { return false; } if (lhs->sharding().IsTileMaximal()) { return MaybeImproveInstructionSharding(lhs->sharding(), instruction, may_combine_partial_sharding); } if (IsConvolutionKernelSmall(instruction)) { // If the kernel is small compared to the input then we can generate an // output what is sharded the same way as the input. const auto& tile_assignment = lhs->sharding().tile_assignment(); if (tile_assignment.dim(dnums.input_feature_dimension()) > 1) { return false; } return MaybeImproveInstructionSharding(get_tiled_sharding_based_on_lhs(), instruction, may_combine_partial_sharding); } // If the kernel is large (e.g., backward convolution) then we only support // replicated output. We intend to keep the sharding along the batch dimension // between lhs and output. return MaybeImproveInstructionSharding( hlo_sharding_util::PartiallyReplicateTiledShardingOnAllDimsExcept( lhs->sharding(), {dnums.input_batch_dimension()}), instruction, may_combine_partial_sharding); } [&](const HloInstruction* inst, absl::Span< const dot_as_convolution_util::DotConvolutionDimsInfo::DimNums> dims, int lhs_or_rhs) { int64_t partitions = 1; if (!inst->has_sharding()) { return partitions; } const auto& sharding = inst->sharding(); if (sharding.IsTileMaximal()) { return partitions; } for (const auto& dim : dims) { if (lhs_or_rhs == 0) { partitions *= sharding.tile_assignment().dim(dim.lhs); } else { CHECK_EQ(lhs_or_rhs, 1); partitions *= sharding.tile_assignment().dim(dim.rhs); } } return partitions; }; auto get_tiled_sharding_based_on_lhs = [&] { CHECK(!lhs->sharding().IsTileMaximal()); std::vector<int64_t> output_to_lhs_indices(instruction->shape().rank()); output_to_lhs_indices[dnums.output_batch_dimension()] = dnums.input_batch_dimension(); output_to_lhs_indices[dnums.output_feature_dimension()] = dnums.input_feature_dimension(); for (int64_t i = 0; i < dnums.input_spatial_dimensions_size(); ++i) { output_to_lhs_indices[dnums.output_spatial_dimensions(i)] = dnums.input_spatial_dimensions(i); } return hlo_sharding_util::TransposeSharding(lhs->sharding(), output_to_lhs_indices); }; std::optional<HloSharding> InferBroadcastOperandSharding( const HloInstruction& instruction, bool is_spmd) { if (instruction.sharding().IsReplicated() || instruction.sharding().IsManual()) { return instruction.sharding(); } std::vector<int64_t> dims_to_replicate; bool needs_replication = false; for (int64_t i = 0; i < instruction.shape().rank(); ++i) { if (absl::c_count(instruction.dimensions(), i) == 0) { dims_to_replicate.push_back(i); if (instruction.sharding().tile_assignment().dim(i) > 1) { needs_replication = true; } } } // If not SPMD, only support when none of the partitioned dimensions in // the broadcast output belong to new dimensions. if (!is_spmd && needs_replication) { return std::nullopt; } return hlo_sharding_util::RemoveShapeDimensions( hlo_sharding_util::PartiallyReplicateTiledShardingOnDims( instruction.sharding(), dims_to_replicate), dims_to_replicate); } bool InferReduceShardingFromOperand(HloInstruction* instruction, bool may_combine_partial_sharding, bool is_spmd) { auto get_maybe_tuple_sharding = [&](HloSharding sharding) { if (instruction->shape().IsArray()) { return sharding; } std::vector<HloSharding> tuple(instruction->shape().tuple_shapes_size(), std::move(sharding)); return HloSharding::Tuple(instruction->shape(), tuple); }; auto* reduce = Cast<HloReduceInstruction>(instruction); bool changed = false; for (HloInstruction* operand : reduce->inputs()) { if (!hlo_sharding_util::IsSpatiallyPartitioned(operand)) { continue; } if (operand->sharding().IsReplicated() || (!is_spmd && absl::c_any_of(instruction->dimensions(), [operand](int64_t dim) { return operand->sharding().tile_assignment().dim(dim) > 1; }))) { // We are reducing along one of the sharded dimensions. We only // support this in SPMD. changed |= MaybeImproveInstructionSharding( get_maybe_tuple_sharding( hlo_sharding_util::ReplicateAllDataDims(operand->sharding())), reduce, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); continue; } auto after_partial_replication = operand->sharding().IsReplicated() ? operand->sharding() : hlo_sharding_util::PartiallyReplicateTiledShardingOnDims( operand->sharding(), reduce->dimensions()); if (after_partial_replication.IsReplicated()) { changed |= MaybeImproveInstructionSharding( get_maybe_tuple_sharding(after_partial_replication), reduce, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); continue; } // Use the same sharding for all tuple elements, because they are part // of the same reduce instruction. HloSharding new_sharding = get_maybe_tuple_sharding(hlo_sharding_util::RemoveShapeDimensions( after_partial_replication, reduce->dimensions())); changed |= MaybeImproveInstructionSharding( std::move(new_sharding), reduce, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(reduce) == 1); } return changed; } auto get_maybe_tuple_sharding = [&](HloSharding sharding) { if (instruction->shape().IsArray()) { return sharding; } std::vector<HloSharding> tuple(instruction->shape().tuple_shapes_size(), std::move(sharding)); return HloSharding::Tuple(instruction->shape(), tuple); }; absl::c_any_of(instruction->dimensions(), [operand](int64_t dim) { return operand->sharding().tile_assignment().dim(dim) > 1; }))) { absl::StatusOr<bool> ProcessShardingInstruction( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads, bool replace_sharding_with_copy, absl::flat_hash_map<const HloInstruction*, std::vector<int64_t>>* unspecified_dims, std::vector<HloSharding>* saved_root_shardings, absl::flat_hash_map<int64_t, HloSharding>* saved_parameter_shardings, absl::flat_hash_map<HloInstruction*, int64_t>* instruction_to_shard_group_id, absl::flat_hash_map<int64_t, absl::flat_hash_set<HloInstruction*>>* shard_group_id_to_shard_as_group, absl::flat_hash_map<int64_t, absl::flat_hash_set<HloInstruction*>>* shard_group_id_to_shard_like_group, const std::vector<bool>* allow_spmd_sharding_propagation_to_parameters_vector) { bool changed = false; const bool use_shard_group = instruction_to_shard_group_id && shard_group_id_to_shard_as_group && shard_group_id_to_shard_like_group; // Process shard group instruction and returns if current instruction needs // to be removed. auto process_shard_group_instruction = [&](HloInstruction* instruction, bool replaced_with_copy) -> absl::StatusOr<bool> { // Run shard group processing IFF it's not CSE prevention. if (replace_sharding_with_copy) { if (use_shard_group && instruction->has_sharding() && instruction->sharding().IsShardGroup()) { if (instruction->IsCustomCall("Sharding")) { CHECK(instruction->operand(0)->opcode() != HloOpcode::kParameter || (allow_spmd_sharding_propagation_to_parameters_vector && allow_spmd_sharding_propagation_to_parameters_vector->size() == module->entry_computation()->num_parameters() && allow_spmd_sharding_propagation_to_parameters_vector->at( instruction->operand(0)->parameter_number()))); } if (instruction->IsCustomCall("Sharding") && !replaced_with_copy) { // Pass shard group to operand sharding custom-call if it's not // replaced with a copy, meaning that the shardings are to annotate // shard_group. HloSharding operand_sharding = instruction->operand(0)->has_sharding() ? instruction->operand(0)->sharding() : HloSharding::Unknown(); operand_sharding.SetShardGroup( instruction->sharding().GetShardGroup()); instruction->mutable_operand(0)->set_sharding( std::move(operand_sharding)); return true; } else { // Otherwise store the shard group relations. const int64_t shard_group_id = instruction->sharding().GetShardGroup().shard_group_id; (*instruction_to_shard_group_id)[instruction] = shard_group_id; if (instruction->sharding().IsShardAs()) { auto& shard_as_group = (*shard_group_id_to_shard_as_group)[shard_group_id]; if (!shard_as_group.empty()) { CHECK(ShapeUtil::SameDimensions( instruction->shape(), (*shard_as_group.begin())->shape())) << "Instruction: " << instruction->ToString() << " has different shape from the shapes of the other " "instructions within the same shard_as group: " << (*shard_as_group.begin())->shape().ToString(); } shard_as_group.insert(instruction); } else { auto& shard_like_group = (*shard_group_id_to_shard_like_group)[shard_group_id]; if (!shard_like_group.empty()) { CHECK(ShapeUtil::SameDimensions( instruction->shape(), (*shard_like_group.begin())->shape())) << "Instruction: " << instruction->ToString() << " has different shape from the shapes of the other " "instructions within the same shard_like group: " << (*shard_like_group.begin())->shape().ToString(); } shard_like_group.insert(instruction); } HloSharding sharding = instruction->sharding(); sharding.ClearShardGroup(); instruction->set_sharding(std::move(sharding)); } } } return false; }; for (HloComputation* computation : module->computations(execution_threads)) { auto instructions = computation->MakeInstructionPostOrder(); for (auto it = instructions.rbegin(); it != instructions.rend(); ++it) { HloInstruction* instruction = *it; if (instruction->IsCustomCall("Sharding")) { HloSharding original_sharding = instruction->sharding(); TF_RET_CHECK(instruction->has_sharding()) << "Sharding instruction must have a sharding attribute"; VLOG(3) << "ProcessShardingInstruction: " << instruction->ToString(); std::vector<int64_t> unspec_dims; TF_RETURN_IF_ERROR(sharding_op_util::ParseAttributes( Cast<HloCustomCallInstruction>(instruction)->opaque(), &unspec_dims)); bool replaced_with_copy = replace_sharding_with_copy && (!original_sharding.IsUnknown() || instruction->operand(0)->opcode() == HloOpcode::kParameter); // Replace the sharding instruction with a copy node so that it does not // need special handling. if (replaced_with_copy) { auto copy = computation->AddInstruction(HloInstruction::CreateUnary( instruction->shape(), HloOpcode::kCopy, instruction->mutable_operand(0))); TF_ASSIGN_OR_RETURN( std::ignore, computation->ReplaceInstruction( instruction, copy, /*preserve_sharding=*/false, /*relay_control_dependency=*/false, /*remove_unused_operands=*/false)); copy->set_sharding(std::move(original_sharding)); instruction = copy; changed = true; } TF_ASSIGN_OR_RETURN( bool shard_group_remove_instruction, process_shard_group_instruction(instruction, replaced_with_copy)); if (!unspec_dims.empty()) { absl::c_sort(unspec_dims); unspecified_dims->emplace(instruction, std::move(unspec_dims)); } else if (!instruction->operand(0)->has_sharding()) { instruction->mutable_operand(0)->set_sharding( instruction->sharding()); } if (shard_group_remove_instruction) { TF_ASSIGN_OR_RETURN(std::ignore, computation->ReplaceInstruction( instruction, instruction->mutable_operand(0), /*preserve_sharding=*/false, /*relay_control_dependency=*/false, /*remove_unused_operands=*/false)); } } else { TF_ASSIGN_OR_RETURN(std::ignore, process_shard_group_instruction( instruction, /*replaced_with_copy=*/false)); } } } // Save the original shardings of parameters/outputs. HloInstruction* root_instr = module->entry_computation()->root_instruction(); if (saved_root_shardings != nullptr && root_instr->shape().IsTuple() && root_instr->has_sharding()) { saved_root_shardings->reserve( root_instr->sharding().tuple_elements().size()); for (const HloSharding& sharding : root_instr->sharding().tuple_elements()) { saved_root_shardings->push_back(sharding); } } if (saved_parameter_shardings != nullptr) { auto params = module->entry_computation()->parameter_instructions(); for (int64_t i = 0; i < params.size(); ++i) { if (params[i]->has_sharding()) { saved_parameter_shardings->insert({i, params[i]->sharding()}); } } } return changed; } [&](HloInstruction* instruction, bool replaced_with_copy) -> absl::StatusOr<bool> { // Run shard group processing IFF it's not CSE prevention. if (replace_sharding_with_copy) { if (use_shard_group && instruction->has_sharding() && instruction->sharding().IsShardGroup()) { if (instruction->IsCustomCall("Sharding")) { CHECK(instruction->operand(0)->opcode() != HloOpcode::kParameter || (allow_spmd_sharding_propagation_to_parameters_vector && allow_spmd_sharding_propagation_to_parameters_vector->size() == module->entry_computation()->num_parameters() && allow_spmd_sharding_propagation_to_parameters_vector->at( instruction->operand(0)->parameter_number()))); } if (instruction->IsCustomCall("Sharding") && !replaced_with_copy) { // Pass shard group to operand sharding custom-call if it's not // replaced with a copy, meaning that the shardings are to annotate // shard_group. HloSharding operand_sharding = instruction->operand(0)->has_sharding() ? instruction->operand(0)->sharding() : HloSharding::Unknown(); operand_sharding.SetShardGroup( instruction->sharding().GetShardGroup()); instruction->mutable_operand(0)->set_sharding( std::move(operand_sharding)); return true; } else { // Otherwise store the shard group relations. const int64_t shard_group_id = instruction->sharding().GetShardGroup().shard_group_id; (*instruction_to_shard_group_id)[instruction] = shard_group_id; if (instruction->sharding().IsShardAs()) { auto& shard_as_group = (*shard_group_id_to_shard_as_group)[shard_group_id]; if (!shard_as_group.empty()) { CHECK(ShapeUtil::SameDimensions( instruction->shape(), (*shard_as_group.begin())->shape())) << "Instruction: " << instruction->ToString() << " has different shape from the shapes of the other " "instructions within the same shard_as group: " << (*shard_as_group.begin())->shape().ToString(); } shard_as_group.insert(instruction); } else { auto& shard_like_group = (*shard_group_id_to_shard_like_group)[shard_group_id]; if (!shard_like_group.empty()) { CHECK(ShapeUtil::SameDimensions( instruction->shape(), (*shard_like_group.begin())->shape())) << "Instruction: " << instruction->ToString() << " has different shape from the shapes of the other " "instructions within the same shard_like group: " << (*shard_like_group.begin())->shape().ToString(); } shard_like_group.insert(instruction); } HloSharding sharding = instruction->sharding(); sharding.ClearShardGroup(); instruction->set_sharding(std::move(sharding)); } } } return false; }; VLOG(3) << "ProcessShardingInstruction: " << instruction->ToString(); int64_t ComputeNonRootUsers(const HloInstruction* instr) { int64_t non_root_users = instr->users().size(); for (int i = 0; i < instr->users().size(); ++i) { if (instr->users()[i] == instr->parent()->root_instruction()) { --non_root_users; } } return non_root_users; } /*static*/ absl::Status ShardingPropagation::NormalizeDomain( const DomainMetadata::Domain& domain, const DomainMetadata* metadata) { if (metadata != nullptr) { TF_ASSIGN_OR_RETURN(const auto& sharding_metadata, ShardingMetadata::ToShardingMetadata(metadata)); const auto& sharding = sharding_metadata->sharding(); if (sharding != nullptr) { bool is_spatially_partitioned = !sharding->HasUniqueDevice(); if (sharding->IsTuple()) { is_spatially_partitioned = absl::c_any_of( sharding->tuple_elements(), [](const HloSharding& s) { return !s.HasUniqueDevice(); }); } if (is_spatially_partitioned) { for (HloInstruction* d : domain.exit_domains) { HloInstruction* operand = d->mutable_operand(0); // Set sharding only if it is different. We don't overwrite the // metadata if it has the same sharding besides metadata. if (!operand->has_sharding() || operand->sharding() != *sharding) { HloSharding operand_sharding = *sharding; if (operand->shape().IsTuple() && !sharding->IsTuple()) { // Expand sharding into tuple sharding per // CloneShardingForDomain() in // third_party/tensorflow/compiler/xla/hlo/ir/hlo_sharding_metadata.cc operand_sharding = HloSharding::SingleTuple(operand->shape(), *sharding); } operand->set_sharding(std::move(operand_sharding)); } } return absl::OkStatus(); } } } return ShardingMetadata::NormalizeShardingDomain(domain, metadata); } std::optional<HloSharding> ShardingPropagation::GetShardingFromUser( const HloInstruction& instruction, const HloInstruction& user, int64_t aggressiveness, bool is_spmd, const CallGraph& call_graph, const CustomCallShardingHelper* sharding_helper) { if (!CanPropagateThroughAtAggressiveLevel(user, aggressiveness)) { return std::nullopt; } if (!hlo_sharding_util::IsSpatiallyPartitioned(&user)) { return std::nullopt; } const bool may_combine_partial_sharding = is_spmd && aggressiveness > 0; switch (user.opcode()) { case HloOpcode::kBroadcast: { return InferBroadcastOperandSharding(user, is_spmd); } case HloOpcode::kConcatenate: { if (aggressiveness == 0) { return std::nullopt; } if (user.sharding().IsReplicated()) { return user.sharding(); } const int64_t cdim = user.concatenate_dimension(); auto& tile_assignment = user.sharding().tile_assignment(); if (tile_assignment.dim(cdim) == 1) { // If we are concatenating along a non-sharded dimension then the // operands should have the same sharding as the result. return user.sharding(); } if (is_spmd) { // SPMD doesn't support tiling with part of the devices. Return the same // sharding. return user.sharding(); } // If we are concatenating along a sharded dimension then we want the // operands to be distributed among the devices their data is used. int64_t start_offset = 0; for (HloInstruction* op : user.operands()) { if (op == &instruction) { break; } start_offset += op->shape().dimensions(cdim); } const int64_t tile_shape = CeilOfRatio( user.shape().dimensions(cdim), tile_assignment.dimensions()[cdim]); std::vector<int64_t> start_indices(tile_assignment.num_dimensions()); std::vector<int64_t> end_indices(tile_assignment.dimensions().begin(), tile_assignment.dimensions().end()); start_indices[cdim] = start_offset / tile_shape; end_indices[cdim] = CeilOfRatio( start_offset + instruction.shape().dimensions(cdim), tile_shape); auto new_tile_assignment = tile_assignment.array().Slice(start_indices, end_indices); if (new_tile_assignment.num_elements() == 1) { return HloSharding::AssignDevice(*new_tile_assignment.begin(), user.sharding().metadata()); } return HloSharding::Tile(std::move(new_tile_assignment), user.sharding().metadata()); } case HloOpcode::kConvolution: { auto dot_dims = dot_as_convolution_util::ParseConvolutionDimsInfo(&user); if (dot_dims.conv_spatial_dims.empty()) { int64_t op_idx = user.operand_index(&instruction); return hlo_sharding_util::InferDotOperandSharding( &user, op_idx, dot_dims, /*consider_other_operand=*/true, may_combine_partial_sharding); } return std::nullopt; } case HloOpcode::kDynamicSlice: case HloOpcode::kDynamicUpdateSlice: { if (aggressiveness == 0) { return std::nullopt; } if (user.sharding().IsReplicated()) { return user.sharding(); } if (user.opcode() == HloOpcode::kDynamicUpdateSlice && &instruction == user.operand(0)) { return user.sharding(); } const HloInstruction* operand = user.opcode() == HloOpcode::kDynamicSlice ? user.operand(0) : user.operand(1); if (&instruction != operand) { return std::nullopt; } if (is_spmd) { return user.sharding(); } const auto& tile_assignment = user.sharding().tile_assignment(); for (int64_t i = 0; i < user.shape().rank(); ++i) { if (tile_assignment.dim(i) > 1 && user.shape().dimensions(i) != operand->shape().dimensions(i)) { return std::nullopt; } } return user.sharding(); } case HloOpcode::kReduceWindow: { auto* reduce_window = Cast<HloReduceWindowInstruction>(&user); if (!absl::c_linear_search(reduce_window->inputs(), &instruction)) { return std::nullopt; } if (reduce_window->shape().IsTuple()) { auto sub_sharding = reduce_window->sharding().GetSubSharding( reduce_window->shape(), {reduce_window->operand_index(&instruction)}); return sub_sharding; } return reduce_window->sharding(); } case HloOpcode::kReshape: { return hlo_sharding_util::PropagateShardingThroughReshape( user.shape(), instruction.shape(), user.sharding()); } case HloOpcode::kPad: { if (&instruction != user.operand(0)) { return std::nullopt; } return user.sharding(); } case HloOpcode::kSlice: { return user.sharding(); } case HloOpcode::kTranspose: { // Calculate the dimension numbers for reversing the current transpose // and then use TransposeSharding to convert the output sharding to an // input sharding. std::vector<int64_t> reverse_dimensions(user.dimensions().size()); for (int64_t i = 0; i < user.dimensions().size(); ++i) { reverse_dimensions[user.dimensions(i)] = i; } return hlo_sharding_util::TransposeSharding(user.sharding(), reverse_dimensions); } case HloOpcode::kTuple: { auto sub_sharding = user.sharding().GetSubSharding( user.shape(), {user.operand_index(&instruction)}); // In case the instruction is used as the operands multiple times within // this tuple, we will return the most specific sharding and propagate up. for (int64_t i = 0; i < user.shape().tuple_shapes_size(); ++i) { if (user.operand(i) == &instruction) { // Only evaluate GetSubSharding if this operand is of interest, // as it is relatively expensive. HloSharding alternative_sub_sharding = user.sharding().GetSubSharding(user.shape(), {i}); if (hlo_sharding_util::IsShardingMoreSpecific( alternative_sub_sharding, sub_sharding)) { sub_sharding = alternative_sub_sharding; } } } return sub_sharding; } case HloOpcode::kGetTupleElement: { int64_t sharding_index = 0; for (int i = 0; i < instruction.shape().tuple_shapes_size(); ++i) { if (i == user.tuple_index()) { break; } if (instruction.shape().tuple_shapes(i).IsArray()) { sharding_index += 1; } else { sharding_index += ShapeUtil::GetLeafCount(instruction.shape().tuple_shapes(i)); } } if (user.shape().IsArray()) { // Use ReplicateAllDataDims instead of HloSharding::Replicate() to // preserve manual subgroups. HloSharding new_sharding = instruction.has_sharding() ? instruction.sharding() : HloSharding::SingleTuple( instruction.shape(), hlo_sharding_util::ReplicateAllDataDims(user.sharding())); new_sharding.tuple_elements()[sharding_index] = user.sharding(); return new_sharding; } else { if (user.sharding().tuple_elements().empty()) { return std::nullopt; } HloSharding new_sharding = instruction.has_sharding() ? instruction.sharding() : HloSharding::SingleTuple( instruction.shape(), hlo_sharding_util::ReplicateAllDataDims( user.sharding().tuple_elements()[0])); for (int64_t i = 0; i < user.sharding().tuple_elements().size(); ++i) { new_sharding.tuple_elements()[sharding_index + i] = user.sharding().tuple_elements()[i]; } return new_sharding; } } case HloOpcode::kDot: { int64_t op_idx = user.operand_index(&instruction); auto dnums = dot_as_convolution_util::ParseDotGeneralFromDot(&user); return hlo_sharding_util::InferDotOperandSharding( &user, op_idx, dnums, /*consider_other_operand=*/true, may_combine_partial_sharding); } case HloOpcode::kReduce: { if (instruction.shape().rank() == 0) { return std::nullopt; } auto user_sharding = user.shape().IsTuple() ? user.sharding().GetSubSharding( user.shape(), {user.operand_index(&instruction)}) : user.sharding(); if (!user_sharding.IsTileMaximal()) { std::vector<int64_t> target_tile_assignment_dimensions( instruction.shape().rank() + (user_sharding.ReplicateOnLastTileDim() ? 1 : 0) + user_sharding.subgroup_types().size()); const auto& dimensions = user.dimensions(); int64_t next_output_dim = 0; for (int64_t i = 0; i < target_tile_assignment_dimensions.size(); ++i) { if (absl::c_find(dimensions, i) == dimensions.end()) { target_tile_assignment_dimensions[i] = user_sharding.tile_assignment().dim(next_output_dim++); } else { target_tile_assignment_dimensions[i] = 1; } } auto tile_assignment = user_sharding.tile_assignment().Reshape( target_tile_assignment_dimensions); user_sharding = user_sharding.ReplicateOnLastTileDim() ? HloSharding::PartialTile(tile_assignment, user_sharding.metadata()) : HloSharding::Subgroup(tile_assignment, user_sharding.subgroup_types(), user_sharding.metadata()); } // Try to merge with sharding from other operands if they can improve // current sharding. const auto* reduce = Cast<const HloReduceInstruction>(&user); for (const HloInstruction* operand : reduce->inputs()) { if (operand != &instruction && operand->has_sharding()) { hlo_sharding_util::MergeShardingIfCompatible( operand->sharding(), user_sharding.NumTiles() + 1, &user_sharding); } } return user_sharding; } case HloOpcode::kSort: { HloSharding user_sharding = user.sharding(); if (user_sharding.IsTuple()) { return user_sharding.GetSubSharding(user.shape(), {user.operand_index(&instruction)}); } return user_sharding; } case HloOpcode::kReverse: { return hlo_sharding_util::ReverseSharding(user.sharding(), user.dimensions()); } case HloOpcode::kOutfeed: { if (&instruction != user.operand(0)) { return std::nullopt; } std::vector<Shape> operand_shapes(user.operand_count()); for (int i = 0; i < user.operand_count(); ++i) { operand_shapes[i] = user.operand(i)->shape(); } return user.sharding().GetSubSharding( ShapeUtil::MakeTupleShape(operand_shapes), {0}); } case HloOpcode::kGather: { if (&instruction == user.operand(1)) { return hlo_sharding_util:: GatherIndexShardingFromOutputIndexPassthroughDimensions( user.sharding(), &user); } if (is_spmd) { return hlo_sharding_util::GatherOperandShardingFromOutput( user.sharding(), user, call_graph); } return std::nullopt; } case HloOpcode::kScatter: { auto& scatter_user = *Cast<HloScatterInstruction>(&user); const int64_t operand_count = scatter_user.scatter_operand_count(); auto scatter_operands = scatter_user.scatter_operands(); auto scatter_indices = scatter_user.scatter_indices(); auto scatter_updates = scatter_user.scatter_updates(); // Infer sharding for scatter operand. const int64_t operand_index = absl::c_find(scatter_operands, &instruction) - scatter_operands.cbegin(); if (operand_index < operand_count) { return user.sharding().IsTuple() ? user.sharding().GetSubSharding( user.shape(), {operand_index}) : user.sharding(); } // Infer sharding for scatter indices. if (&instruction == scatter_indices) { std::vector<const HloInstruction*> partitioned_updates; for (const HloInstruction* update : scatter_updates) { if (hlo_sharding_util::IsSpatiallyPartitioned(update)) { partitioned_updates.push_back(update); } } if (partitioned_updates.empty()) { return std::nullopt; } std::vector<HloSharding> shardings; absl::c_transform( partitioned_updates, std::back_inserter(shardings), [&scatter_user](const HloInstruction* update) { return hlo_sharding_util:: ScatterIndexShardingFromUpdateIndexPassthroughDimensions( update->sharding(), &scatter_user); }); return hlo_sharding_util::FindCommonSharding(shardings); } // Infer sharding for scatter update. const int64_t update_index = absl::c_find(scatter_updates, &instruction) - scatter_updates.cbegin(); CHECK_LE(update_index, operand_count); auto from_indices = hlo_sharding_util::IsSpatiallyPartitioned(scatter_indices) ? hlo_sharding_util:: ScatterUpdateShardingFromIndexIndexPassthroughDimensions( scatter_indices->sharding(), &scatter_user) : HloSharding::Replicate(); if (is_spmd) { auto from_output = hlo_sharding_util::ScatterUpdateShardingFromOutput( user.sharding().IsTuple() ? user.sharding().GetSubSharding(user.shape(), {update_index}) : user.sharding(), scatter_user, call_graph); if (from_output.has_value()) { // Use sharding from output as primary sharding since it prioritize // parallel sharding first as this is how it is in spmd_partitioner. hlo_sharding_util::MergeShardingIfCompatible( from_indices, from_output->NumTiles() + 1, &*from_output); if (!from_output->IsTileMaximal()) { return from_output; } } } if (!from_indices.IsTileMaximal()) { return from_indices; } return std::nullopt; } case HloOpcode::kCustomCall: { bool compatible_shapes = ShapeUtil::CompatibleIgnoringElementType( instruction.shape(), user.shape()); if (!compatible_shapes) { // Incompatible shapes, we will not propagate sharding. return std::nullopt; } if (!sharding_helper) { // No available sharding helper and shapes are compatible, we will // propagate sharding. return user.sharding(); } if (sharding_helper->CanPropagateShardingToOperands(&user)) { return user.sharding(); } return std::nullopt; } default: { // If the user output shape is compatible with the current instruction // shape excluding element type and the current instruction is supported // by spatial partitioning, then the user sharding can be used for // propagation to the current instruction. if (ShapeUtil::CompatibleIgnoringElementType(instruction.shape(), user.shape())) { return user.sharding(); } return std::nullopt; } } } [&scatter_user](const HloInstruction* update) { return hlo_sharding_util:: ScatterIndexShardingFromUpdateIndexPassthroughDimensions( update->sharding(), &scatter_user); }); bool AggressiveConcatOperandShardingCanPassThrough( const HloInstruction* concat_operand) { return ( hlo_sharding_util::IsSpatiallyPartitioned(concat_operand) && (concat_operand->has_sharding() && concat_operand->sharding().NumTiles() > 1) && concat_operand->opcode() == HloOpcode::kReshape && (concat_operand->operand(0)->opcode() == HloOpcode::kParameter || concat_operand->operand(0)->opcode() == HloOpcode::kGetTupleElement)); } bool InferDynamicSliceOrDynamicUpdateSliceShardingFromOperands( HloInstruction* instruction, int64_t aggressiveness, bool may_combine_partial_sharding) { const HloInstruction* operand = instruction->opcode() == HloOpcode::kDynamicSlice ? instruction->operand(0) : instruction->operand(1); auto slice_dim_is_sharded = [&]() { if (!hlo_sharding_util::IsSpatiallyPartitioned(operand) || operand->sharding().IsManual() || operand->sharding().NumTiles() == 1) { return false; } for (int64_t i = 0; i < instruction->shape().rank(); ++i) { const auto& tile_assignment = operand->sharding().tile_assignment(); if (tile_assignment.dim(i) > 1 && instruction->shape().dimensions(i) != operand->shape().dimensions(i)) { return true; } } return false; }; // Do not pass through sharding annotation at the first iteration // if slice dim is sharded. if (aggressiveness == 0 && slice_dim_is_sharded()) { return false; } auto propagate_slicing = [&]() { if (!hlo_sharding_util::IsSpatiallyPartitioned(operand)) { return false; } if (slice_dim_is_sharded()) { return false; } return MaybeImproveInstructionSharding( operand->sharding(), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); }; auto propagate_base = [&]() { if (instruction->opcode() != HloOpcode::kDynamicUpdateSlice) { return false; } if (!hlo_sharding_util::IsSpatiallyPartitioned(instruction->operand(0))) { return false; } return MaybeImproveInstructionSharding(instruction->operand(0)->sharding(), instruction, may_combine_partial_sharding); }; bool changed = propagate_slicing(); changed |= propagate_base(); return changed; } auto slice_dim_is_sharded = [&]() { if (!hlo_sharding_util::IsSpatiallyPartitioned(operand) || operand->sharding().IsManual() || operand->sharding().NumTiles() == 1) { return false; } for (int64_t i = 0; i < instruction->shape().rank(); ++i) { const auto& tile_assignment = operand->sharding().tile_assignment(); if (tile_assignment.dim(i) > 1 && instruction->shape().dimensions(i) != operand->shape().dimensions(i)) { return true; } } return false; }; auto propagate_slicing = [&]() { if (!hlo_sharding_util::IsSpatiallyPartitioned(operand)) { return false; } if (slice_dim_is_sharded()) { return false; } return MaybeImproveInstructionSharding( operand->sharding(), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); }; auto propagate_base = [&]() { if (instruction->opcode() != HloOpcode::kDynamicUpdateSlice) { return false; } if (!hlo_sharding_util::IsSpatiallyPartitioned(instruction->operand(0))) { return false; } return MaybeImproveInstructionSharding(instruction->operand(0)->sharding(), instruction, may_combine_partial_sharding); }; bool ShardingPropagation::InferShardingFromShardGroup( HloInstruction* instruction, const ComputationMap& computation_map, int64_t aggressiveness, const absl::flat_hash_set<HloInstruction*>& shard_group) { if (!CanPropagateThroughAtAggressiveLevel(*instruction, aggressiveness)) { return false; } // Do not change manual sharding. if (instruction->has_sharding() && instruction->sharding().IsManual()) { return false; } // Do not propagate sharding to ShardBarrierTo custom-call. if (instruction->IsCustomCall(spmd::kShardBarrierTo)) { return false; } // Propagate manual sharding. if (!instruction->has_sharding() || instruction->sharding().IsTileMaximal()) { for (const HloInstruction* member : shard_group) { if (!member->has_sharding() || !member->sharding().IsManual() || member == instruction) { continue; } instruction->set_sharding(member->sharding()); return true; } } const bool may_combine_partial_sharding = is_spmd_ && aggressiveness > 0; bool changed = false; for (const HloInstruction* member : shard_group) { // Do not propagate sharding from ShardBarrierFrom custom-call. if (member == instruction || member->IsCustomCall(spmd::kShardBarrierFrom)) { continue; } changed |= MaybeImproveInstructionSharding(member->sharding(), instruction, may_combine_partial_sharding); } return changed; } bool ShardingPropagation::InferShardingFromOperands( HloInstruction* instruction, const ComputationMap& computation_map, int64_t aggressiveness, const CallGraph& call_graph, const absl::flat_hash_set<absl::string_view>& execution_threads) { if (!CanPropagateThroughAtAggressiveLevel(*instruction, aggressiveness)) { return false; } // Do not change manual sharding. if (instruction->has_sharding() && instruction->sharding().IsManual()) { return false; } // Propagate manual sharding. Avoid tuple shaped HLOs that group independent // together. Reduce, ReduceWindow, and Sort can be tuples but the elements // are correlated, so we propagate manual sharding through them. // For custom-calls with manual operand, the default propagation logic will // just assign manual to the whole custom-call. const bool custom_call_condition = instruction->opcode() == HloOpcode::kCustomCall && instruction->shape().IsTuple(); // For asynchronous instructions with manual operand, we assign manual to the // whole instructions if the async_execution_thread is not in the // execution_threads. const bool async_instr_condition = instruction->IsAsynchronous() && !HloInstruction::IsThreadIncluded(instruction->async_execution_thread(), execution_threads); if ((!instruction->has_sharding() || instruction->sharding().IsTileMaximal()) && (instruction->shape().IsArray() || instruction->opcode() == HloOpcode::kReduce || instruction->opcode() == HloOpcode::kSort || instruction->opcode() == HloOpcode::kReduceWindow || custom_call_condition || async_instr_condition)) { for (const HloInstruction* op : instruction->operands()) { if (!op->has_sharding() || !op->sharding().IsManual()) continue; // Do not pass through manual sharding to SPMDShardToFullShape. if (instruction->IsCustomCall("SPMDShardToFullShape")) { return false; } // Do not pass through manual sharding to concat or dynamic slice when // aggressiveneess is 0. if (aggressiveness == 0 && (instruction->opcode() == HloOpcode::kConcatenate || instruction->opcode() == HloOpcode::kDynamicSlice)) { return false; } instruction->set_sharding( HloSharding::Manual(op->sharding().metadata()) .NormalizeTupleSharding(instruction->shape())); return true; } } const bool may_combine_partial_sharding = is_spmd_ && aggressiveness > 0; if (!SupportSpatialPartitioning( instruction, computation_map, is_spmd_, allow_spmd_sharding_propagation_to_output_, /*allow_spmd_sharding_propagation_to_parameters=*/false, sharding_helper_.get())) { // If an array shaped HLO doesn't support spatial partitioning but at least // one of its operand is replicated then we make the HLO replicated as well. if (instruction->shape().IsTuple() || instruction->operand_count() == 0 || instruction == instruction->parent()->root_instruction() || instruction->HasSideEffect()) { return false; } for (const HloInstruction* op : instruction->operands()) { if (op->has_sharding() && op->sharding().IsTileMaximal() && !op->sharding().HasUniqueDevice()) { return MaybeImproveInstructionSharding(op->sharding(), instruction, may_combine_partial_sharding); } } return false; } auto get_maybe_tuple_sharding = [&](HloSharding sharding) { if (instruction->shape().IsArray()) { return sharding; } std::vector<HloSharding> tuple(instruction->shape().tuple_shapes_size(), std::move(sharding)); return HloSharding::Tuple(instruction->shape(), tuple); }; switch (instruction->opcode()) { case HloOpcode::kGetTupleElement: { const HloInstruction* operand = instruction->operand(0); if (!hlo_sharding_util::IsSpatiallyPartitioned(operand)) { return false; } HloSharding new_sharding = operand->sharding().GetSubSharding( operand->shape(), {instruction->tuple_index()}); if (new_sharding.IsManual()) { instruction->set_sharding(std::move(new_sharding)); return true; } return MaybeImproveInstructionSharding( std::move(new_sharding), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); } case HloOpcode::kTuple: { if (absl::c_none_of( instruction->operands(), [](const HloInstruction* hlo) { return hlo_sharding_util::IsSpatiallyPartitioned(hlo); })) { // None of the operands have a spatially partitioned sharding. return false; } const Shape& shape = instruction->shape(); // Go through each operand and if the operand has a sharding that is // better than the current sharding for that tuple element then update // it. If the current sharding does not exist, assume its replicated. std::vector<HloSharding> sub_shardings; if (instruction->has_sharding()) { sub_shardings = instruction->sharding().tuple_elements(); } else { // If instruction does not have a sharding, assume its replicated to // allow refinement. sub_shardings.assign(HloSharding::RequiredLeaves(shape), HloSharding::Replicate()); } // This is required to allow manual sharding on operands to be propagated // to the tuple. hlo_sharding_util::IsShardingMoreSpecific() returns false // if any of the shardings involved is manual, so using it directly will // prevent manual sharding on an operand to be propagated to the tuple // when it has no existing sharding. auto is_more_specific = [instruction](const HloSharding& operand_sharding, const HloSharding& existing) { // If the instruction originally had no sharding, always prefer operand // sharding. return !instruction->has_sharding() || hlo_sharding_util::IsShardingMoreSpecific(operand_sharding, existing); }; int64_t sub_sharding_index = 0; for (int64_t i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const HloInstruction* operand = instruction->operand(i); if (operand->has_sharding()) { if (operand->shape().IsTuple()) { for (int64_t j = 0, e = ShapeUtil::GetLeafCount(operand->shape()); j < e; ++j) { if (is_more_specific(operand->sharding().tuple_elements()[j], sub_shardings[sub_sharding_index + j])) { sub_shardings[sub_sharding_index + j] = operand->sharding().tuple_elements()[j]; } } } else { std::optional<HloSharding> op_sharding = hlo_sharding_util::GetOutputSharding(operand); CHECK(op_sharding.has_value()) << "Expected sharding for " << operand->ToString(); if (is_more_specific(op_sharding.value(), sub_shardings[sub_sharding_index])) { sub_shardings[sub_sharding_index] = op_sharding.value(); } } } sub_sharding_index += ShapeUtil::GetLeafCount(operand->shape()); } HloSharding new_sharding = HloSharding::Tuple(shape, sub_shardings); if (!instruction->has_sharding() || new_sharding != instruction->sharding()) { instruction->set_sharding(std::move(new_sharding)); return true; } return false; } case HloOpcode::kReduce: { // Reduce could have a tuple shape, where the first half of operands are // the arrays to reduce, and the second half of operands are the init // values. return InferReduceShardingFromOperand( instruction, may_combine_partial_sharding, is_spmd_); } case HloOpcode::kBroadcast: { // Make forward propagation through broadcast low priority to avoid // resharding after broadcast. if (aggressiveness < 3) { return false; } const HloInstruction* op = instruction->operand(0); if (!hlo_sharding_util::IsSpatiallyPartitioned(op) || op->sharding().IsReplicated()) { return false; } // The output will be tiled along the broadcasted dimension the same way // as the input for the broadcast while the other dimensions are kept // non-tiled. std::vector<int64_t> target_tile_assignment_dimensions; const auto& dimensions = instruction->dimensions(); for (int64_t i = 0; i < instruction->shape().rank(); ++i) { auto it = absl::c_find(dimensions, i); if (it == dimensions.end()) { target_tile_assignment_dimensions.push_back(1); } else { const int64_t source_dim = std::distance(dimensions.begin(), it); target_tile_assignment_dimensions.push_back( op->sharding().tile_assignment().dim(source_dim)); } } for (int64_t i = op->sharding().TiledDataRank(); i < op->sharding().tile_assignment().num_dimensions(); ++i) { target_tile_assignment_dimensions.push_back( op->sharding().tile_assignment().dim(i)); } auto new_tile_assignment = op->sharding().tile_assignment().Reshape( target_tile_assignment_dimensions); HloSharding new_sharding = op->sharding().ReplicateOnLastTileDim() ? HloSharding::PartialTile(new_tile_assignment, op->sharding().metadata()) : HloSharding::Subgroup(new_tile_assignment, op->sharding().subgroup_types(), op->sharding().metadata()); return MaybeImproveInstructionSharding( std::move(new_sharding), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ComputeNonRootUsers(instruction) == 1); } case HloOpcode::kConcatenate: { const HloInstruction* operand = PickRepresentativeOperand(instruction); if (!operand || !hlo_sharding_util::IsSpatiallyPartitioned(operand)) { return false; } if (aggressiveness == 0) { for (const HloInstruction* concat_operand : instruction->operands()) { if (!AggressiveConcatOperandShardingCanPassThrough(concat_operand)) { return false; } const auto& tile_assignment = concat_operand->sharding().tile_assignment(); for (int64_t i = 0; i < instruction->shape().rank(); ++i) { if (absl::c_linear_search(instruction->dimensions(), i) && tile_assignment.dim(i) > 1) { return false; } } } } return MaybeImproveInstructionSharding( operand->sharding(), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ComputeNonRootUsers(instruction) == 1); } case HloOpcode::kConvolution: return InferConvolutionShardingFromOperands( instruction, call_graph, aggressiveness, may_combine_partial_sharding, is_spmd_); case HloOpcode::kTranspose: { const HloInstruction* input = instruction->operand(0); if (!hlo_sharding_util::IsSpatiallyPartitioned(input)) { return false; } HloSharding sharding = hlo_sharding_util::TransposeSharding( input->sharding(), instruction->dimensions()); return MaybeImproveInstructionSharding( std::move(sharding), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ComputeNonRootUsers(instruction) == 1); } case HloOpcode::kReduceWindow: { auto* reduce_window = Cast<HloReduceWindowInstruction>(instruction); auto has_dilation = [](const WindowDimension& dimensions) { return dimensions.base_dilation() > 1 || dimensions.window_dilation() > 1; }; if (absl::c_any_of(instruction->window().dimensions(), has_dilation)) { VLOG(2) << "Not applying sharding to reduce window because dilatation " "isn't supported yet: " << reduce_window->ToString(); return false; } bool changed = false; for (HloInstruction* operand : reduce_window->inputs()) { if (!hlo_sharding_util::IsSpatiallyPartitioned(operand)) { continue; } changed |= MaybeImproveInstructionSharding( get_maybe_tuple_sharding(operand->sharding()), reduce_window, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); } return changed; } case HloOpcode::kSelectAndScatter: { // Shard according to first operand, as output keeps the same shape. const HloInstruction* lhs = instruction->operand(0); if (!hlo_sharding_util::IsSpatiallyPartitioned(lhs)) { return false; } auto has_base_dilation = [](const WindowDimension& dimensions) { return dimensions.base_dilation() > 1; }; if (absl::c_any_of(instruction->window().dimensions(), has_base_dilation)) { VLOG(2) << "Not applying sharding to select-and-scatter because " "base dilation isn't supported yet: " << instruction->ToString(); return false; } return MaybeImproveInstructionSharding( lhs->sharding(), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ComputeNonRootUsers(instruction) == 1); } case HloOpcode::kReshape: { if (!hlo_sharding_util::IsSpatiallyPartitioned(instruction->operand(0))) { return false; } HloSharding new_sharding = hlo_sharding_util::PropagateShardingThroughReshape( instruction->operand(0)->shape(), instruction->shape(), instruction->operand(0)->sharding()); return MaybeImproveInstructionSharding( std::move(new_sharding), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); return false; } case HloOpcode::kReverse: { const HloInstruction* operand = instruction->operand(0); if (!hlo_sharding_util::IsSpatiallyPartitioned(operand)) { return false; } return MaybeImproveInstructionSharding( hlo_sharding_util::ReverseSharding(operand->sharding(), instruction->dimensions()), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ComputeNonRootUsers(instruction) == 1); } case HloOpcode::kDot: { const auto& dnums = dot_as_convolution_util::ParseDotGeneralFromDot(instruction); return InferDotShardingFromOperands(instruction, call_graph, dnums, may_combine_partial_sharding, is_spmd_); } case HloOpcode::kParameter: { auto parent_it = computation_map.find(instruction->parent()); if (parent_it == computation_map.end()) { return false; } const HloInstruction* parent = parent_it->second; switch (parent->opcode()) { case HloOpcode::kConditional: { for (int64_t i = 1; i < parent->operand_count(); ++i) { if (parent->called_computations()[i - 1] == instruction->parent()) { if (parent->operand(i)->has_sharding()) { return MaybeImproveInstructionSharding( parent->operand(i)->sharding(), instruction, may_combine_partial_sharding); } return false; } } return false; } case HloOpcode::kCall: { int64_t i = instruction->parameter_number(); if (parent->operand(i)->has_sharding()) { return MaybeImproveInstructionSharding( parent->operand(i)->sharding(), instruction, may_combine_partial_sharding); } return false; } default: return false; } } case HloOpcode::kSort: { const HloInstruction* operand = PickRepresentativeOperand(instruction); if (!operand || !hlo_sharding_util::IsSpatiallyPartitioned(operand)) { return false; } HloSortInstruction* sort = DynCast<HloSortInstruction>(instruction); CHECK(sort); const int64_t sort_dim = sort->sort_dimension(); if (!operand->sharding().IsTileMaximal() && operand->sharding().tile_assignment().dim(sort_dim) != 1) { // In case of a sort operand sharded along the sort dimension, the // sharding is propagated only if there exists a free (unsharded) // dimension that we can later move the sharding into. if (!hlo_sharding_util::IsSortOperandShardingMovable(operand, sort_dim)) return false; } if (instruction->shape().IsTuple()) { return MaybeImproveInstructionSharding( HloSharding::SingleTuple(instruction->shape(), operand->sharding()), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); } else { return MaybeImproveInstructionSharding( operand->sharding(), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); } } case HloOpcode::kDynamicSlice: case HloOpcode::kDynamicUpdateSlice: { return InferDynamicSliceOrDynamicUpdateSliceShardingFromOperands( instruction, aggressiveness, may_combine_partial_sharding); } case HloOpcode::kGather: { bool changed = false; if (hlo_sharding_util::IsSpatiallyPartitioned(instruction->operand(1))) { HloSharding new_sharding = hlo_sharding_util:: GatherOutputShardingFromIndexIndexPassthroughDimensions( instruction->operand(1)->sharding(), instruction); changed |= MaybeImproveInstructionSharding( std::move(new_sharding), instruction, may_combine_partial_sharding); } if (is_spmd_) { auto gather_parallel_dims = hlo_sharding_util::GetGatherParallelBatchDims(*instruction, call_graph); if (gather_parallel_dims) { changed |= InferGatherParallelShardingFromOperands( instruction, *gather_parallel_dims, may_combine_partial_sharding); } if (hlo_sharding_util::IsSpatiallyPartitioned( instruction->operand(0))) { absl::Span<const int64_t> operand_parallel_dims; if (gather_parallel_dims) { operand_parallel_dims = absl::MakeConstSpan( gather_parallel_dims->operand_parallel_dims); } HloSharding filtered_operand_sharding = hlo_sharding_util::PartiallyReplicateTiledShardingOnDims( instruction->operand(0)->sharding(), operand_parallel_dims); auto maybe_from_data = hlo_sharding_util:: GatherOutputShardingFromOperandOperandPassthroughDimensions( filtered_operand_sharding, *instruction); if (maybe_from_data) { changed |= MaybeImproveInstructionSharding( std::move(*maybe_from_data), instruction, may_combine_partial_sharding); } } } return changed; } case HloOpcode::kScatter: { auto& scatter = *Cast<HloScatterInstruction>(instruction); const int64_t operand_count = scatter.scatter_operand_count(); auto scatter_operands = scatter.scatter_operands(); auto scatter_indices = scatter.scatter_indices(); auto scatter_updates = scatter.scatter_updates(); bool changed = false; if (is_spmd_) { for (int64_t i = 0; i != operand_count; ++i) { if (hlo_sharding_util::IsSpatiallyPartitioned(scatter_operands[i])) { changed |= MaybeImproveInstructionSubSharding( scatter_operands[i]->sharding(), instruction, {i}, may_combine_partial_sharding); } } if (!hlo_sharding_util::IsSpatiallyPartitioned(scatter_indices) && absl::c_none_of(scatter_updates, [](const HloInstruction* update) { return hlo_sharding_util::IsSpatiallyPartitioned(update); })) { return changed; } auto scatter_parallel_dims = hlo_sharding_util::GetScatterParallelBatchDims(*instruction, call_graph); if (scatter_parallel_dims) { changed |= InferScatterParallelShardingFromOperands( instruction, *scatter_parallel_dims, may_combine_partial_sharding); } for (int64_t i = 0; i != operand_count; ++i) { if (hlo_sharding_util::IsSpatiallyPartitioned(scatter_updates[i])) { auto maybe_from_update = hlo_sharding_util::ScatterOutputShardingFromUpdate( scatter_updates[i]->sharding(), scatter); if (maybe_from_update) { changed |= MaybeImproveInstructionSubSharding( std::move(*maybe_from_update), instruction, {i}, may_combine_partial_sharding); } } } } else { for (int64_t i = 0; i != operand_count; ++i) { changed |= MaybeImproveInstructionSubSharding( HloSharding::Replicate(), instruction, {i}, may_combine_partial_sharding); } } return changed; } case HloOpcode::kWhile: { if (!instruction->operand(0)->has_sharding()) { return false; } auto sharding = instruction->operand(0)->sharding(); if (instruction->has_sharding()) { hlo_sharding_util::MergeSharding(instruction->sharding(), &sharding, may_combine_partial_sharding); } return MaybeImproveInstructionSharding(std::move(sharding), instruction, may_combine_partial_sharding); } case HloOpcode::kCustomCall: { HloSharding inferred_operand_sharding = HloSharding::Replicate(); if (auto* partitioner = GetCustomCallPartitioner(instruction->custom_call_target()); partitioner && partitioner->IsCustomCallShardable(instruction)) { if (auto sharding = partitioner->InferShardingFromOperands(instruction)) { inferred_operand_sharding = *sharding; } else { return false; } } else if (sharding_helper_->IsCustomCallShardable(instruction)) { if (auto sharding = sharding_helper_->InferShardingFromOperands(instruction)) { inferred_operand_sharding = *sharding; } else { return false; } } else { const HloInstruction* operand = PickRepresentativeOperand(instruction); if (!operand || !hlo_sharding_util::IsSpatiallyPartitioned(operand)) { return false; } inferred_operand_sharding = operand->sharding(); } return MaybeImproveInstructionSharding( inferred_operand_sharding, instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ComputeNonRootUsers(instruction) == 1); } default: { if (instruction->IsElementwise() && may_combine_partial_sharding) { bool changed = false; for (auto operand : instruction->operands()) { if (hlo_sharding_util::IsSpatiallyPartitioned(operand)) { if (instruction->opcode() == HloOpcode::kRng) { // Rng is considered elementwise but has operands with different // shapes. changed |= MaybeImproveInstructionSharding( hlo_sharding_util::ReplicateAllDataDims( operand->sharding(), instruction->shape().rank()), instruction, may_combine_partial_sharding, ComputeNonRootUsers(instruction) == 1); continue; } changed |= MaybeImproveInstructionSharding( operand->sharding(), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ instruction->operands().size() == 1 && ComputeNonRootUsers(instruction) == 1); } } return changed; } const HloInstruction* operand = PickRepresentativeOperand(instruction); if (!operand || !hlo_sharding_util::IsSpatiallyPartitioned(operand)) { return false; } return MaybeImproveInstructionSharding( operand->sharding(), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ComputeNonRootUsers(instruction) == 1); } } return false; } // NOLINT(readability/fn_size) auto get_maybe_tuple_sharding = [&](HloSharding sharding) { if (instruction->shape().IsArray()) { return sharding; } std::vector<HloSharding> tuple(instruction->shape().tuple_shapes_size(), std::move(sharding)); return HloSharding::Tuple(instruction->shape(), tuple); }; auto is_more_specific = [instruction](const HloSharding& operand_sharding, const HloSharding& existing) { // If the instruction originally had no sharding, always prefer operand // sharding. return !instruction->has_sharding() || hlo_sharding_util::IsShardingMoreSpecific(operand_sharding, existing); }; VLOG(2) << "Not applying sharding to reduce window because dilatation " VLOG(2) << "Not applying sharding to select-and-scatter because " bool ShardingPropagation::InferShardingFromUsers( HloInstruction* instruction, const ShardingPropagation::ComputationMap& computation_map, int64_t aggressiveness, bool is_spmd, const CustomCallShardingHelper* sharding_helper, const CallGraph& call_graph) { if (aggressiveness < 2 && instruction->opcode() == HloOpcode::kBroadcast) { return false; } // Do not change manual sharding. if (instruction->has_sharding() && instruction->sharding().IsManual()) { return false; } // Propagate manual sharding. if (!instruction->has_sharding() || instruction->sharding().IsTileMaximal()) { for (const HloInstruction* user : instruction->users()) { if (!user->has_sharding() || user->IsCustomCall("SPMDFullToShardShape")) continue; if (instruction->shape().IsArray() && user->sharding().IsManual()) { instruction->set_sharding( HloSharding::Manual(user->sharding().metadata())); return true; } else { std::optional<HloSharding> user_sharding = ShardingPropagation::GetShardingFromUser( *instruction, *user, aggressiveness, is_spmd, call_graph, sharding_helper); if (user_sharding && user_sharding->IsManual()) { instruction->set_sharding(std::move(*user_sharding)); return true; } } } } if (!SupportSpatialPartitioning( instruction, computation_map, is_spmd, /*allow_spmd_sharding_propagation_to_output=*/false, allow_spmd_sharding_propagation_to_parameters_, sharding_helper)) { return false; } bool improved_sharding = false; const bool may_combine_partial_sharding = is_spmd && aggressiveness > 0; for (const HloInstruction* user : instruction->users()) { std::optional<HloSharding> user_sharding = ShardingPropagation::GetShardingFromUser(*instruction, *user, aggressiveness, is_spmd, call_graph, sharding_helper); if (user_sharding && instruction->opcode() == HloOpcode::kCustomCall) { if (auto* partitioner = GetCustomCallPartitioner(instruction->custom_call_target())) { if (partitioner->IsCustomCallShardable(instruction)) { user_sharding = partitioner->PropagateUserSharding(instruction, user, *user_sharding); } } else if (sharding_helper->IsCustomCallShardable(instruction)) { user_sharding = sharding_helper->PropagateUserSharding( instruction, user, *user_sharding); } } if (user_sharding) { improved_sharding |= MaybeImproveInstructionSharding( std::move(*user_sharding), instruction, may_combine_partial_sharding); } } return improved_sharding; } absl::StatusOr<bool> ShardingPropagation::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { // Register custom-call partitioner for SharBarrierFrom and ShardBarrierTo. ABSL_CONST_INIT static absl::once_flag did_registration; absl::call_once(did_registration, [] { RegisterCustomCallPartitioner( spmd::kShardBarrierFrom, std::make_unique<spmd::ShardBarrierFromPartitioner>()); RegisterCustomCallPartitioner( spmd::kShardBarrierTo, std::make_unique<spmd::ShardBarrierToPartitioner>()); }); std::optional<absl::flat_hash_map<const HloInstruction*, HloSharding>> original_sharding; bool any_changed = false; // Preprocessing for CSE prevention propagation: record the original shardings // so that we can revert to them at the end, and only keep those on CSE // prevention instructions. if (cse_prevention_only_) { original_sharding.emplace(); for (auto computation : module->computations(execution_threads)) { for (auto instruction : computation->instructions()) { if (instruction->has_sharding()) { original_sharding->emplace(instruction, instruction->sharding()); } } } } else { // The current pass is not for CSE prevention, but we remove the shardings // added by previous passes for CSE prevention. for (auto computation : module->computations(execution_threads)) { for (auto instruction : computation->instructions()) { if (instruction->has_sharding() && IsCSEPreventionSharding(instruction->sharding())) { instruction->clear_sharding(); any_changed = true; } } } } any_changed |= propagate_metadata_ ? AssignShardingMetadata(module, execution_threads) : RemoveShardingMetadata(module, execution_threads); absl::flat_hash_map<const HloInstruction*, std::vector<int64_t>> unspecified_dims; std::vector<HloSharding> saved_root_shardings; absl::flat_hash_map<int64_t, HloSharding> saved_parameter_shardings; absl::flat_hash_map<HloInstruction*, int64_t> instruction_to_shard_group_id; absl::flat_hash_map<int64_t, absl::flat_hash_set<HloInstruction*>> shard_group_id_to_shard_as_group; absl::flat_hash_map<int64_t, absl::flat_hash_set<HloInstruction*>> shard_group_id_to_shard_like_group; TF_ASSIGN_OR_RETURN( bool changed, ProcessShardingInstruction( module, execution_threads, !cse_prevention_only_, &unspecified_dims, allow_spmd_sharding_propagation_to_output_ ? &saved_root_shardings : nullptr, allow_spmd_sharding_propagation_to_parameters_ ? &saved_parameter_shardings : nullptr, &instruction_to_shard_group_id, &shard_group_id_to_shard_as_group, &shard_group_id_to_shard_like_group, &allow_spmd_sharding_propagation_to_parameters_vector_)); any_changed |= changed; for (const auto& [shard_group_id, shard_as_group] : shard_group_id_to_shard_as_group) { VLOG(5) << "Shard-As group " << shard_group_id << " contains:"; for (auto instruction : shard_as_group) { VLOG(5) << " " << instruction->ToString(); } } for (const auto& [shard_group_id, shard_like_group] : shard_group_id_to_shard_like_group) { VLOG(5) << "Shard-Like group " << shard_group_id << " contains:"; for (auto instruction : shard_like_group) { VLOG(5) << " " << instruction->ToString(); } } // Check sizes of the given allow_spmd_sharding_propagation vectors if (allow_spmd_sharding_propagation_to_output_) { CHECK(!module->entry_computation()->root_instruction()->has_sharding() || allow_spmd_sharding_propagation_to_output_vector_.size() == 1 || module->entry_computation() ->root_instruction() ->sharding() .tuple_elements() .size() == allow_spmd_sharding_propagation_to_output_vector_.size()) << "allow-spmd-sharding-propagation-to-output-vector's size can be " "either 1 or the number of elements in the root tuple of entry " "computation."; } if (allow_spmd_sharding_propagation_to_parameters_) { auto is_same_sized_tuple = [](HloModule* module, int64_t size) { if (module->entry_computation()->num_parameters() != 1) { return false; } HloInstruction* param = module->entry_computation()->parameter_instruction(0); return param->shape().IsTuple() && size == param->shape().tuple_shapes_size(); }; auto size = allow_spmd_sharding_propagation_to_parameters_vector_.size(); CHECK(size == 1 || size == module->entry_computation()->num_parameters() || is_same_sized_tuple(module, size)) << "allow-spmd-sharding-propagation-to-parameters-vector's size can be " "either 1 or the number of parameters in the entry computation."; } // Association of partitionable embedded computations with their parent // instruction. ComputationMap computation_map; // Instructions that are related through a computation and need to share the // same sharding. auto get_related_instructions = [this](HloInstruction* inst) { if (inst->opcode() == HloOpcode::kWhile) { return std::vector<HloInstruction*>{ inst, inst->while_body()->root_instruction(), inst->while_body()->parameter_instruction(0), inst->while_condition()->parameter_instruction(0)}; } else if (inst->opcode() == HloOpcode::kConditional) { const auto& called_computations = inst->called_computations(); std::vector<HloInstruction*> comps; comps.reserve(called_computations.size() + 1); comps.push_back(inst); for (HloComputation* c : called_computations) { comps.push_back(c->root_instruction()); } return comps; } else if (inst->opcode() == HloOpcode::kCustomCall) { if (sharding_helper_ && sharding_helper_->IsCustomCallShardable(inst)) { return sharding_helper_->GetRelatedInstructions(inst); } else { return std::vector<HloInstruction*>{}; } } else if (inst->opcode() == HloOpcode::kCall) { HloComputation* callee = inst->called_computations().front(); return std::vector<HloInstruction*>{inst, callee->root_instruction()}; } else { CHECK(false); } }; // If instruction is a while, or the root or a parameter of a while body, // then propagate its sharding to the while instruction, to its body root, // and to its condition parameter. std::function<void(HloInstruction*, absl::flat_hash_set<HloInstruction*>*)> maybe_computation_propagation = [&](HloInstruction* instruction, absl::flat_hash_set<HloInstruction*>* changed) { auto propagate_to_instruction = [&](HloInstruction* search_inst) { auto related_instructions = get_related_instructions(search_inst); if (absl::c_count(related_instructions, instruction)) { for (HloInstruction* inst : related_instructions) { if (!inst->has_sharding() || inst->sharding() != instruction->sharding()) { VLOG(2) << "Add computation sharding: " << inst->name() << " " << instruction->sharding().ToString(); inst->copy_sharding(instruction); changed->insert(inst); maybe_computation_propagation(inst, changed); } } } }; if (instruction->opcode() == HloOpcode::kConditional || instruction->opcode() == HloOpcode::kWhile || instruction->opcode() == HloOpcode::kCustomCall || instruction->opcode() == HloOpcode::kCall) { propagate_to_instruction(instruction); } if (instruction->opcode() == HloOpcode::kParameter || instruction->parent()->root_instruction() == instruction) { auto it = computation_map.find(instruction->parent()); if (it != computation_map.end()) { propagate_to_instruction(it->second); } } }; for (auto computation : module->computations(execution_threads)) { for (auto instruction : computation->instructions()) { if (instruction->opcode() == HloOpcode::kWhile) { TF_RETURN_IF_ERROR( CheckAndUpdateDeviceAssignmentsInWhileBody(instruction)); } } } // Populate computation_map in order to associate while bodies to their // while instructions. for (auto computation : module->computations(execution_threads)) { for (auto instruction : computation->instructions()) { if (instruction->opcode() == HloOpcode::kWhile || instruction->opcode() == HloOpcode::kConditional || instruction->opcode() == HloOpcode::kCall) { // Check if any of the related instructions has sharding, in which case // propagate it to the other instructions, so they all share the same // sharding, in case the user didn't shard all of them. We don't check // that user shardings are consistent, because such check is already // done by HLO verifier. const HloInstruction* sharded_inst = nullptr; auto related_instructions = get_related_instructions(instruction); for (auto inst : related_instructions) { if (inst->has_sharding()) { sharded_inst = inst; break; } } if (sharded_inst != nullptr) { // Set the same sharding to all the other related instructions. for (auto inst : related_instructions) { inst->copy_sharding(sharded_inst); } } if (instruction->opcode() == HloOpcode::kWhile) { computation_map[instruction->while_body()] = instruction; } else { for (HloComputation* c : instruction->called_computations()) { computation_map[c] = instruction; } } } } } // Collect all pre-sharded instructions as we aren't allowed to modify their // sharding. absl::flat_hash_set<const HloInstruction*> provided_shardings; for (const HloComputation* computation : module->computations(execution_threads)) { for (const HloInstruction* inst : computation->instructions()) { if (inst->has_sharding() && inst != module->entry_computation()->root_instruction() && inst->opcode() != HloOpcode::kParameter && !inst->sharding().IsUnknown()) { provided_shardings.insert(inst); } } } if (!allow_spmd_sharding_propagation_to_output_ && (!module->entry_computation()->root_instruction()->has_sharding() || !module->entry_computation() ->root_instruction() ->sharding() .IsUnknown())) { // Consider the root instruction of the entry module as one with provided // sharding as its sharding have to match with the one expected by the host. provided_shardings.insert(module->entry_computation()->root_instruction()); } if (!allow_spmd_sharding_propagation_to_parameters_) { for (auto param : module->entry_computation()->parameter_instructions()) { if (param->has_sharding() && !param->sharding().IsUnknown()) { provided_shardings.insert(param); } } } // Replace all unknown shardings with replicated sharding for propagation. for (HloComputation* computation : module->computations(execution_threads)) { auto instructions = computation->MakeInstructionPostOrder(); for (auto it = instructions.rbegin(); it != instructions.rend(); ++it) { HloInstruction* instruction = *it; if (instruction->has_sharding() && instruction->sharding().IsUnknown()) { instruction->set_sharding( HloSharding::Replicate(instruction->sharding().metadata())); } } } // Iterate to a fixpoint that is guaranteed to be reached because we only // strictly improve the sharding of the graph and it can't be improved // indefinitely. int64_t iterations = 0; std::unique_ptr<CallGraph> call_graph = CallGraph::Build(module); auto run_to_fix_point = [&](int64_t aggressiveness, bool propagate_shard_group) { absl::flat_hash_set<const HloInstruction*> already_inferred_from_shard_group; absl::flat_hash_set<const HloInstruction*> already_inferred_from_operands; absl::flat_hash_set<const HloInstruction*> already_inferred_from_users; bool changed_last_iter = true; const bool may_merge_partial = is_spmd_ && aggressiveness > 0; while (changed_last_iter) { changed_last_iter = false; int64_t inferred_from_shard_group_counter = 0; int64_t inferred_from_operand_counter = 0; int64_t inferred_from_user_counter = 0; int64_t instruction_counter = 0; int64_t already_sharded_counter = 0; for (const HloComputation* computation : module->computations(execution_threads)) { VLOG(2) << "Consider computation: " << computation->name(); std::vector<HloInstruction*> instructions = computation->MakeInstructionPostOrder(); instruction_counter += instructions.size(); already_sharded_counter += absl::c_count_if( instructions, [](const HloInstruction* inst) { return inst->has_sharding(); }); auto clear_cache = [&](HloInstruction* hlo, HloInstruction* hlo_for_users = nullptr) { for (auto operand : hlo->operands()) { already_inferred_from_users.erase(operand); } if (hlo_for_users == nullptr) { hlo_for_users = hlo; } for (auto user : hlo_for_users->users()) { already_inferred_from_operands.erase(user); // If the user has called computations, then the parameter // instructions of these called computations are also removed from // already_inferred_from_operands. for (auto c : user->called_computations()) { for (auto parameter : c->parameter_instructions()) { already_inferred_from_operands.erase(parameter); } } } if (instruction_to_shard_group_id.contains(hlo)) { const int64_t shard_group_id = instruction_to_shard_group_id.at(hlo); const absl::flat_hash_set<HloInstruction*>& shard_group = shard_group_id_to_shard_as_group.contains(shard_group_id) ? shard_group_id_to_shard_as_group.at(shard_group_id) : shard_group_id_to_shard_like_group.at(shard_group_id); for (HloInstruction* member : shard_group) { if (member != hlo) { already_inferred_from_shard_group.erase(member); } } } }; // 1. Iterate the shard groups to take shardings from instructions of // the same group. if (propagate_shard_group) { for (HloInstruction* instruction : instructions) { if (already_inferred_from_shard_group.contains(instruction)) { continue; } if (!instruction_to_shard_group_id.contains(instruction)) { continue; } const int64_t shard_group_id = instruction_to_shard_group_id.at(instruction); const absl::flat_hash_set<HloInstruction*>& shard_group = shard_group_id_to_shard_as_group.contains(shard_group_id) ? shard_group_id_to_shard_as_group.at(shard_group_id) : shard_group_id_to_shard_like_group.at(shard_group_id); if (provided_shardings.contains(instruction)) { if (!may_merge_partial) { continue; } auto it = unspecified_dims.find(instruction); if (it != unspecified_dims.end() && InferUnspecifiedDimsFromShardGroup(instruction, it->second, shard_group)) { ++inferred_from_shard_group_counter; VLOG(2) << "Refined partial sharding (shard group): " << instruction->ToString(); clear_cache(instruction); already_inferred_from_shard_group.insert(instruction); changed_last_iter = true; } continue; } already_inferred_from_shard_group.insert(instruction); if (InferShardingFromShardGroup(instruction, computation_map, aggressiveness, shard_group)) { ++inferred_from_shard_group_counter; any_changed = true; VLOG(2) << "Add sharding (shard group): " << instruction->ToString(); absl::flat_hash_set<HloInstruction*> changed_in_comp_prop; maybe_computation_propagation(instruction, &changed_in_comp_prop); clear_cache(instruction); for (auto hlo : changed_in_comp_prop) { clear_cache(hlo); } changed_last_iter = true; } } } // 2. Iterate the HLO graph in post order taking shardings from // operands. for (HloInstruction* instruction : instructions) { if (already_inferred_from_operands.contains(instruction)) { continue; } if (provided_shardings.contains(instruction)) { if (!may_merge_partial) { continue; } auto it = unspecified_dims.find(instruction); HloInstruction* man_conversion_op_after; if (it != unspecified_dims.end() && InferUnspecifiedDimsFromOperand(instruction, it->second, &man_conversion_op_after)) { ++inferred_from_operand_counter; VLOG(2) << "Refined partial sharding (forward-pass): " << instruction->ToString(); clear_cache(instruction, man_conversion_op_after); already_inferred_from_operands.insert(instruction); changed_last_iter = true; } continue; } already_inferred_from_operands.insert(instruction); if (InferShardingFromOperands(instruction, computation_map, aggressiveness, *call_graph, execution_threads)) { ++inferred_from_operand_counter; any_changed = true; VLOG(2) << "Add sharding (forward-pass): " << instruction->ToString(); absl::flat_hash_set<HloInstruction*> changed_in_comp_prop; maybe_computation_propagation(instruction, &changed_in_comp_prop); clear_cache(instruction); for (auto hlo : changed_in_comp_prop) { clear_cache(hlo); } changed_last_iter = true; } } // 3. Iterate the HLO graph in reverse post order taking shardings from // users. for (auto it = instructions.rbegin(); it != instructions.rend(); ++it) { if ((*it)->IsCustomCall("SPMDFullToShardShape") || (*it)->IsCustomCall("SPMDShardToFullShape")) { // The manual conversion op is processed together with the sharding // op before it. If the conversion op is removed from cache, the // sharding op should also be removed. if (!already_inferred_from_users.contains(*it)) { already_inferred_from_users.erase((*it)->operand(0)); } } if (already_inferred_from_users.contains(*it)) { continue; } if (provided_shardings.contains(*it)) { if (!may_merge_partial) { continue; } auto uit = unspecified_dims.find(*it); HloInstruction* man_conversion_op_after; if (uit != unspecified_dims.end() && InferUnspecifiedDimsFromUsers( *it, uit->second, aggressiveness, is_spmd_, &man_conversion_op_after, *call_graph)) { ++inferred_from_user_counter; VLOG(2) << "Refined partial sharding (backward-pass): " << (*it)->ToString(); clear_cache(*it, man_conversion_op_after); already_inferred_from_users.insert(*it); if (man_conversion_op_after != nullptr) { already_inferred_from_users.insert(man_conversion_op_after); } changed_last_iter = true; } continue; } already_inferred_from_users.insert(*it); if (InferShardingFromUsers(*it, computation_map, aggressiveness, is_spmd_, sharding_helper_.get(), *call_graph)) { ++inferred_from_user_counter; any_changed = true; VLOG(2) << "Add sharding (backward-pass): " << (*it)->ToString(); absl::flat_hash_set<HloInstruction*> changed_in_comp_prop; maybe_computation_propagation(*it, &changed_in_comp_prop); clear_cache(*it); for (auto hlo : changed_in_comp_prop) { clear_cache(hlo); } changed_last_iter = true; } } } VLOG(1) << "Sharding propagation iteration " << iterations << ";" << "\n total instructions: " << instruction_counter << "\n instructions already sharded: " << already_sharded_counter << "\n shardings inferred from shard group: " << inferred_from_shard_group_counter << "\n shardings inferred from operands: " << inferred_from_operand_counter << "\n shardings inferred from users: " << inferred_from_user_counter << "\n aggressiveness: " << aggressiveness; ++iterations; } return absl::OkStatus(); }; for (int64_t aggressiveness = 0; aggressiveness < 4; ++aggressiveness) { TF_RETURN_IF_ERROR( run_to_fix_point(aggressiveness, /*propagate_shard_group=*/true)); } // Align the shardings from the same shard_as group so that they will adopt // the same sharding. for (const auto& [shard_as_group_id, shard_as_group] : shard_group_id_to_shard_as_group) { // If all the inferred shardings of the instructions from the same shard // group are compatible with each other, then we will merge all of them to // get the most specific sharding. If some of them are not compatible, then // it will just choose the a random sharding among them(say the first one), // with the guarantee that the defaultly chosen sharding will not be from a // ShardBarrierFrom op if there is one within the ShardAs group. HloSharding default_sharding = HloSharding::Replicate(); std::vector<HloSharding> shardings; for (HloInstruction* instruction : shard_as_group) { if (instruction->has_sharding()) { shardings.push_back(instruction->sharding()); if (!instruction->IsCustomCall(spmd::kShardBarrierFrom) && default_sharding.IsReplicated()) { default_sharding = instruction->sharding(); } } } HloSharding common_sharding = hlo_sharding_util::FindCommonSharding(shardings, default_sharding); VLOG(2) << "Aligning shard group: " << shard_as_group_id << " to sharding:" << common_sharding.ToString(); for (HloInstruction* member : shard_as_group) { if (member->IsCustomCall(spmd::kShardBarrierTo)) { continue; } if (provided_shardings.contains(member)) { auto it = unspecified_dims.find(member); if (it != unspecified_dims.end()) { HloSharding partial_replicated = hlo_sharding_util::PartiallyReplicateTiledShardingOnAllDimsExcept( common_sharding, it->second); HloSharding sharding = member->sharding(); if (hlo_sharding_util::MergeShardingIfCompatible( partial_replicated, sharding.NumTiles() + 1, &sharding)) { member->set_sharding(sharding); } } } member->set_sharding(common_sharding); } } // If a ShardBarrierFrom custom-call op is in a shard as group, and relay // the shard as sharding to its original op, do not relay shardings for // ShardbarrierTo op. Then run sharding propagation once more at highest // aggressiveness without propagating shard group. for (HloComputation* computation : module->computations(execution_threads)) { for (HloInstruction* instruction : computation->instructions()) { if (instruction->IsCustomCall(spmd::kShardBarrierFrom) && instruction_to_shard_group_id.contains(instruction) && shard_group_id_to_shard_as_group.contains( instruction_to_shard_group_id.at(instruction))) { HloSharding sharding = instruction->sharding(); hlo_sharding_util::MergeShardingIfCompatible( instruction->mutable_operand(0)->sharding(), sharding.NumTiles(), &sharding); instruction->mutable_operand(0)->set_sharding(std::move(sharding)); } } } TF_RETURN_IF_ERROR( run_to_fix_point(/*aggressiveness=*/3, /*propagate_shard_group=*/false)); // Post-process to remove all "shard-barrier-from" and "shard-barrier-to" // custom-calls. for (HloComputation* computation : module->computations(execution_threads)) { for (HloInstruction* instruction : computation->instructions()) { // If a ShardBarrierFrom custom-call op is in a shard as group, and relay // the shard as sharding to its original op, do not relay shardings for // ShardbarrierTo op. if (instruction->IsCustomCall(spmd::kShardBarrierFrom) && instruction_to_shard_group_id.contains(instruction) && shard_group_id_to_shard_as_group.contains( instruction_to_shard_group_id.at(instruction))) { HloSharding sharding = instruction->sharding(); hlo_sharding_util::MergeShardingIfCompatible( instruction->mutable_operand(0)->sharding(), sharding.NumTiles(), &sharding); instruction->mutable_operand(0)->set_sharding(std::move(sharding)); } if (instruction->IsCustomCall(spmd::kShardBarrierFrom) || instruction->IsCustomCall(spmd::kShardBarrierTo)) { TF_ASSIGN_OR_RETURN(std::ignore, computation->ReplaceInstruction( instruction, instruction->mutable_operand(0), /*preserve_sharding=*/false, /*relay_control_dependency=*/false, /*remove_unused_operands=*/false)); } } } // Post-process for CSE prevention. if (cse_prevention_only_) { for (auto computation : module->computations(execution_threads)) { for (auto instruction : computation->instructions()) { if (!instruction->has_sharding()) { continue; } if (IsCSEPreventionTarget(instruction) && instruction->has_sharding()) { if (!(*original_sharding).contains(instruction)) { // Mark the propagated sharding as for CSE prevention. instruction->set_sharding( SetCSEPreventionSharding(instruction->sharding())); } continue; } auto it = (*original_sharding).find(instruction); if (it != (*original_sharding).end()) { // Revert sharding. instruction->set_sharding(it->second); } else { // Clear sharding. instruction->clear_sharding(); } } } } HloInstruction* root_instruction = module->entry_computation()->root_instruction(); if (saved_root_shardings.size() == allow_spmd_sharding_propagation_to_output_vector_.size() && root_instruction->has_sharding()) { HloSharding root_sharding = root_instruction->sharding(); for (int i = 0; i < saved_root_shardings.size(); ++i) { if (!allow_spmd_sharding_propagation_to_output_vector_[i] && !saved_root_shardings[i].IsUnknown()) { root_sharding.tuple_elements()[i] = saved_root_shardings[i]; } } root_instruction->set_sharding(std::move(root_sharding)); } auto params = module->entry_computation()->parameter_instructions(); if (allow_spmd_sharding_propagation_to_parameters_) { if (allow_spmd_sharding_propagation_to_parameters_vector_.size() == params.size()) { for (int64_t i = 0; i < params.size(); ++i) { if (!allow_spmd_sharding_propagation_to_parameters_vector_[i]) { if (saved_parameter_shardings.contains(i) && !saved_parameter_shardings.at(i).IsUnknown()) { params[i]->set_sharding(saved_parameter_shardings.at(i)); } else { params[i]->clear_sharding(); } } } } else if (params.size() == 1 && saved_parameter_shardings.size() == 1 && params[0]->shape().IsTuple() && params[0]->shape().tuple_shapes_size() == allow_spmd_sharding_propagation_to_parameters_vector_ .size()) { // There is a single parameter which is a tuple with many elements. HloSharding param_sharding = params[0]->sharding(); for (int64_t i = 0; i < params[0]->shape().tuple_shapes_size(); ++i) { HloSharding saved_subsharding = saved_parameter_shardings.at(0).GetSubSharding(params[0]->shape(), {i}); if (!allow_spmd_sharding_propagation_to_parameters_vector_[i] && !saved_subsharding.IsUnknown()) { param_sharding.tuple_elements()[i] = saved_subsharding; } } params[0]->set_sharding(std::move(param_sharding)); } } // Replicate the parameter/output sharding if the propagated sharding does not // evenly partition the parameter/output. std::function<bool(const Shape&, const HloSharding&)> evenly_partitions = [&evenly_partitions](const Shape& shape, const HloSharding& sharding) -> bool { if (!sharding.IsTiled()) { return true; } if (sharding.IsTileMaximal()) { return sharding.IsReplicated(); } if (sharding.IsTuple()) { for (int64_t i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { if (!evenly_partitions(ShapeUtil::GetTupleElementShape(shape, i), sharding.GetSubSharding(shape, {i}))) { return false; } } } for (int64_t i = 0; i < shape.dimensions_size(); ++i) { if (shape.dimensions(i) % sharding.tile_assignment().dim(i) != 0) { return false; } } return true; }; if (allow_spmd_sharding_propagation_to_output_ && root_instruction->has_sharding()) { if (root_instruction->shape().IsTuple() && allow_spmd_sharding_propagation_to_output_vector_.size() == root_instruction->shape().tuple_shapes_size()) { // The output shape is a tuple and sharding propagation is allowed for at // least one of its elements. HloSharding root_sharding = root_instruction->sharding(); for (int64_t i = 0; i < root_instruction->shape().tuple_shapes_size(); ++i) { if (allow_spmd_sharding_propagation_to_output_vector_[i] && !evenly_partitions(root_instruction->shape().tuple_shapes(i), root_sharding.tuple_elements()[i])) { root_sharding.tuple_elements()[i] = HloSharding::Replicate(); } } root_instruction->set_sharding(std::move(root_sharding)); } else if (!root_instruction->shape().IsTuple()) { // The output shape is not tuple and sharding propagation is allowed. if (!evenly_partitions(root_instruction->shape(), root_instruction->sharding())) { root_instruction->set_sharding(HloSharding::Replicate()); } } } if (allow_spmd_sharding_propagation_to_parameters_) { // Sharding propagation is allowed for at least one parameter. if (allow_spmd_sharding_propagation_to_parameters_vector_.size() == params.size()) { for (int64_t i = 0; i < params.size(); ++i) { if (params[i]->has_sharding() && allow_spmd_sharding_propagation_to_parameters_vector_[i] && !evenly_partitions(params[i]->shape(), params[i]->sharding())) { params[i]->set_sharding(HloSharding::Replicate()); } } } else if (params.size() == 1 && params[0]->shape().IsTuple() && params[0]->has_sharding() && params[0]->shape().tuple_shapes_size() == allow_spmd_sharding_propagation_to_parameters_vector_ .size()) { HloSharding param_sharding = params[0]->sharding(); for (int64_t i = 0; i < params[0]->shape().tuple_shapes_size(); ++i) { if (allow_spmd_sharding_propagation_to_parameters_vector_[i] && !evenly_partitions( ShapeUtil::GetSubshapeOneIndex(params[0]->shape(), i), params[0]->sharding().GetSubSharding(params[0]->shape(), {i}))) { param_sharding.tuple_elements()[i] = HloSharding::Replicate(); } } params[0]->set_sharding(std::move(param_sharding)); } } TF_RETURN_IF_ERROR( hlo_sharding_util::CanonicalizeLayoutAfterShardingPropagation( module, allow_spmd_sharding_propagation_to_output_, allow_spmd_sharding_propagation_to_parameters_)); VLOG(1) << "Sharding propagation completed after " << iterations << " iterations"; return any_changed; } absl::call_once(did_registration, [] { RegisterCustomCallPartitioner( spmd::kShardBarrierFrom, std::make_unique<spmd::ShardBarrierFromPartitioner>()); RegisterCustomCallPartitioner( spmd::kShardBarrierTo, std::make_unique<spmd::ShardBarrierToPartitioner>()); }); VLOG(5) << "Shard-As group " << shard_group_id << " contains:"; VLOG(5) << " " << instruction->ToString(); VLOG(5) << "Shard-Like group " << shard_group_id << " contains:"; VLOG(5) << " " << instruction->ToString(); auto is_same_sized_tuple = [](HloModule* module, int64_t size) { if (module->entry_computation()->num_parameters() != 1) { return false; } HloInstruction* param = module->entry_computation()->parameter_instruction(0); return param->shape().IsTuple() && size == param->shape().tuple_shapes_size(); }; auto get_related_instructions = [this](HloInstruction* inst) { if (inst->opcode() == HloOpcode::kWhile) { return std::vector<HloInstruction*>{ inst, inst->while_body()->root_instruction(), inst->while_body()->parameter_instruction(0), inst->while_condition()->parameter_instruction(0)}; } else if (inst->opcode() == HloOpcode::kConditional) { const auto& called_computations = inst->called_computations(); std::vector<HloInstruction*> comps; comps.reserve(called_computations.size() + 1); comps.push_back(inst); for (HloComputation* c : called_computations) { comps.push_back(c->root_instruction()); } return comps; } else if (inst->opcode() == HloOpcode::kCustomCall) { if (sharding_helper_ && sharding_helper_->IsCustomCallShardable(inst)) { return sharding_helper_->GetRelatedInstructions(inst); } else { return std::vector<HloInstruction*>{}; } } else if (inst->opcode() == HloOpcode::kCall) { HloComputation* callee = inst->called_computations().front(); return std::vector<HloInstruction*>{inst, callee->root_instruction()}; } else { CHECK(false); } }; [&](HloInstruction* instruction, absl::flat_hash_set<HloInstruction*>* changed) { auto propagate_to_instruction = [&](HloInstruction* search_inst) { auto related_instructions = get_related_instructions(search_inst); if (absl::c_count(related_instructions, instruction)) { for (HloInstruction* inst : related_instructions) { if (!inst->has_sharding() || inst->sharding() != instruction->sharding()) { VLOG(2) << "Add computation sharding: " << inst->name() << " " << instruction->sharding().ToString(); inst->copy_sharding(instruction); changed->insert(inst); maybe_computation_propagation(inst, changed); } } } }; if (instruction->opcode() == HloOpcode::kConditional || instruction->opcode() == HloOpcode::kWhile || instruction->opcode() == HloOpcode::kCustomCall || instruction->opcode() == HloOpcode::kCall) { propagate_to_instruction(instruction); } if (instruction->opcode() == HloOpcode::kParameter || instruction->parent()->root_instruction() == instruction) { auto it = computation_map.find(instruction->parent()); if (it != computation_map.end()) { propagate_to_instruction(it->second); } } }; auto propagate_to_instruction = [&](HloInstruction* search_inst) { auto related_instructions = get_related_instructions(search_inst); if (absl::c_count(related_instructions, instruction)) { for (HloInstruction* inst : related_instructions) { if (!inst->has_sharding() || inst->sharding() != instruction->sharding()) { VLOG(2) << "Add computation sharding: " << inst->name() << " " << instruction->sharding().ToString(); inst->copy_sharding(instruction); changed->insert(inst); maybe_computation_propagation(inst, changed); } } } }; VLOG(2) << "Add computation sharding: " << inst->name() auto run_to_fix_point = [&](int64_t aggressiveness, bool propagate_shard_group) { absl::flat_hash_set<const HloInstruction*> already_inferred_from_shard_group; absl::flat_hash_set<const HloInstruction*> already_inferred_from_operands; absl::flat_hash_set<const HloInstruction*> already_inferred_from_users; bool changed_last_iter = true; const bool may_merge_partial = is_spmd_ && aggressiveness > 0; while (changed_last_iter) { changed_last_iter = false; int64_t inferred_from_shard_group_counter = 0; int64_t inferred_from_operand_counter = 0; int64_t inferred_from_user_counter = 0; int64_t instruction_counter = 0; int64_t already_sharded_counter = 0; for (const HloComputation* computation : module->computations(execution_threads)) { VLOG(2) << "Consider computation: " << computation->name(); std::vector<HloInstruction*> instructions = computation->MakeInstructionPostOrder(); instruction_counter += instructions.size(); already_sharded_counter += absl::c_count_if( instructions, [](const HloInstruction* inst) { return inst->has_sharding(); }); auto clear_cache = [&](HloInstruction* hlo, HloInstruction* hlo_for_users = nullptr) { for (auto operand : hlo->operands()) { already_inferred_from_users.erase(operand); } if (hlo_for_users == nullptr) { hlo_for_users = hlo; } for (auto user : hlo_for_users->users()) { already_inferred_from_operands.erase(user); // If the user has called computations, then the parameter // instructions of these called computations are also removed from // already_inferred_from_operands. for (auto c : user->called_computations()) { for (auto parameter : c->parameter_instructions()) { already_inferred_from_operands.erase(parameter); } } } if (instruction_to_shard_group_id.contains(hlo)) { const int64_t shard_group_id = instruction_to_shard_group_id.at(hlo); const absl::flat_hash_set<HloInstruction*>& shard_group = shard_group_id_to_shard_as_group.contains(shard_group_id) ? shard_group_id_to_shard_as_group.at(shard_group_id) : shard_group_id_to_shard_like_group.at(shard_group_id); for (HloInstruction* member : shard_group) { if (member != hlo) { already_inferred_from_shard_group.erase(member); } } } }; // 1. Iterate the shard groups to take shardings from instructions of // the same group. if (propagate_shard_group) { for (HloInstruction* instruction : instructions) { if (already_inferred_from_shard_group.contains(instruction)) { continue; } if (!instruction_to_shard_group_id.contains(instruction)) { continue; } const int64_t shard_group_id = instruction_to_shard_group_id.at(instruction); const absl::flat_hash_set<HloInstruction*>& shard_group = shard_group_id_to_shard_as_group.contains(shard_group_id) ? shard_group_id_to_shard_as_group.at(shard_group_id) : shard_group_id_to_shard_like_group.at(shard_group_id); if (provided_shardings.contains(instruction)) { if (!may_merge_partial) { continue; } auto it = unspecified_dims.find(instruction); if (it != unspecified_dims.end() && InferUnspecifiedDimsFromShardGroup(instruction, it->second, shard_group)) { ++inferred_from_shard_group_counter; VLOG(2) << "Refined partial sharding (shard group): " << instruction->ToString(); clear_cache(instruction); already_inferred_from_shard_group.insert(instruction); changed_last_iter = true; } continue; } already_inferred_from_shard_group.insert(instruction); if (InferShardingFromShardGroup(instruction, computation_map, aggressiveness, shard_group)) { ++inferred_from_shard_group_counter; any_changed = true; VLOG(2) << "Add sharding (shard group): " << instruction->ToString(); absl::flat_hash_set<HloInstruction*> changed_in_comp_prop; maybe_computation_propagation(instruction, &changed_in_comp_prop); clear_cache(instruction); for (auto hlo : changed_in_comp_prop) { clear_cache(hlo); } changed_last_iter = true; } } } // 2. Iterate the HLO graph in post order taking shardings from // operands. for (HloInstruction* instruction : instructions) { if (already_inferred_from_operands.contains(instruction)) { continue; } if (provided_shardings.contains(instruction)) { if (!may_merge_partial) { continue; } auto it = unspecified_dims.find(instruction); HloInstruction* man_conversion_op_after; if (it != unspecified_dims.end() && InferUnspecifiedDimsFromOperand(instruction, it->second, &man_conversion_op_after)) { ++inferred_from_operand_counter; VLOG(2) << "Refined partial sharding (forward-pass): " << instruction->ToString(); clear_cache(instruction, man_conversion_op_after); already_inferred_from_operands.insert(instruction); changed_last_iter = true; } continue; } already_inferred_from_operands.insert(instruction); if (InferShardingFromOperands(instruction, computation_map, aggressiveness, *call_graph, execution_threads)) { ++inferred_from_operand_counter; any_changed = true; VLOG(2) << "Add sharding (forward-pass): " << instruction->ToString(); absl::flat_hash_set<HloInstruction*> changed_in_comp_prop; maybe_computation_propagation(instruction, &changed_in_comp_prop); clear_cache(instruction); for (auto hlo : changed_in_comp_prop) { clear_cache(hlo); } changed_last_iter = true; } } // 3. Iterate the HLO graph in reverse post order taking shardings from // users. for (auto it = instructions.rbegin(); it != instructions.rend(); ++it) { if ((*it)->IsCustomCall("SPMDFullToShardShape") || (*it)->IsCustomCall("SPMDShardToFullShape")) { // The manual conversion op is processed together with the sharding // op before it. If the conversion op is removed from cache, the // sharding op should also be removed. if (!already_inferred_from_users.contains(*it)) { already_inferred_from_users.erase((*it)->operand(0)); } } if (already_inferred_from_users.contains(*it)) { continue; } if (provided_shardings.contains(*it)) { if (!may_merge_partial) { continue; } auto uit = unspecified_dims.find(*it); HloInstruction* man_conversion_op_after; if (uit != unspecified_dims.end() && InferUnspecifiedDimsFromUsers( *it, uit->second, aggressiveness, is_spmd_, &man_conversion_op_after, *call_graph)) { ++inferred_from_user_counter; VLOG(2) << "Refined partial sharding (backward-pass): " << (*it)->ToString(); clear_cache(*it, man_conversion_op_after); already_inferred_from_users.insert(*it); if (man_conversion_op_after != nullptr) { already_inferred_from_users.insert(man_conversion_op_after); } changed_last_iter = true; } continue; } already_inferred_from_users.insert(*it); if (InferShardingFromUsers(*it, computation_map, aggressiveness, is_spmd_, sharding_helper_.get(), *call_graph)) { ++inferred_from_user_counter; any_changed = true; VLOG(2) << "Add sharding (backward-pass): " << (*it)->ToString(); absl::flat_hash_set<HloInstruction*> changed_in_comp_prop; maybe_computation_propagation(*it, &changed_in_comp_prop); clear_cache(*it); for (auto hlo : changed_in_comp_prop) { clear_cache(hlo); } changed_last_iter = true; } } } VLOG(1) << "Sharding propagation iteration " << iterations << ";" << "\n total instructions: " << instruction_counter << "\n instructions already sharded: " << already_sharded_counter << "\n shardings inferred from shard group: " << inferred_from_shard_group_counter << "\n shardings inferred from operands: " << inferred_from_operand_counter << "\n shardings inferred from users: " << inferred_from_user_counter << "\n aggressiveness: " << aggressiveness; ++iterations; } return absl::OkStatus(); }; VLOG(2) << "Consider computation: " << computation->name(); auto clear_cache = [&](HloInstruction* hlo, HloInstruction* hlo_for_users = nullptr) { for (auto operand : hlo->operands()) { already_inferred_from_users.erase(operand); } if (hlo_for_users == nullptr) { hlo_for_users = hlo; } for (auto user : hlo_for_users->users()) { already_inferred_from_operands.erase(user); // If the user has called computations, then the parameter // instructions of these called computations are also removed from // already_inferred_from_operands. for (auto c : user->called_computations()) { for (auto parameter : c->parameter_instructions()) { already_inferred_from_operands.erase(parameter); } } } if (instruction_to_shard_group_id.contains(hlo)) { const int64_t shard_group_id = instruction_to_shard_group_id.at(hlo); const absl::flat_hash_set<HloInstruction*>& shard_group = shard_group_id_to_shard_as_group.contains(shard_group_id) ? shard_group_id_to_shard_as_group.at(shard_group_id) : shard_group_id_to_shard_like_group.at(shard_group_id); for (HloInstruction* member : shard_group) { if (member != hlo) { already_inferred_from_shard_group.erase(member); } } } }; VLOG(2) << "Refined partial sharding (shard group): " VLOG(2) << "Add sharding (shard group): " VLOG(2) << "Refined partial sharding (forward-pass): " VLOG(2) << "Add sharding (forward-pass): " VLOG(2) << "Refined partial sharding (backward-pass): " VLOG(2) << "Add sharding (backward-pass): " << (*it)->ToString(); VLOG(1) << "Sharding propagation iteration " << iterations << ";" VLOG(2) << "Aligning shard group: " << shard_as_group_id [&evenly_partitions](const Shape& shape, const HloSharding& sharding) -> bool { if (!sharding.IsTiled()) { return true; } if (sharding.IsTileMaximal()) { return sharding.IsReplicated(); } if (sharding.IsTuple()) { for (int64_t i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { if (!evenly_partitions(ShapeUtil::GetTupleElementShape(shape, i), sharding.GetSubSharding(shape, {i}))) { return false; } } } for (int64_t i = 0; i < shape.dimensions_size(); ++i) { if (shape.dimensions(i) % sharding.tile_assignment().dim(i) != 0) { return false; } } return true; }; VLOG(1) << "Sharding propagation completed after " << iterations
#include "xla/service/sharding_propagation.h" #include <ostream> #include <string> #include <utility> #include <vector> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/log/check.h" #include "absl/log/log.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/ir/hlo_op_metadata.h" #include "xla/hlo/ir/hlo_sharding.h" #include "xla/hlo/transforms/hlo_constant_splitter.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/protobuf_util.h" #include "xla/service/hlo_dce.h" #include "xla/service/hlo_parser.h" #include "xla/tests/hlo_test_base.h" #include "xla/util.h" #include "xla/xla_data.pb.h" #include "tsl/platform/statusor.h" TEST_F(ShardingPropagationTest, PropagateToParametersFull2) { const char* const hlo_string = R"( HloModule module ENTRY %entry { %param0 = f32[4] parameter(0), sharding={replicated} %param1 = f32[4] parameter(1) ROOT %add = f32[4] add(%param0, %param1), sharding={devices=[4]0,1,2,3} })"; TF_ASSERT_OK_AND_ASSIGN(auto module, ParseAndReturnVerifiedModule(hlo_string)); TF_ASSERT_OK_AND_ASSIGN( bool changed, ShardingPropagation( /*is_spmd=*/true, /*propagate_metadata=*/true, /*allow_spmd_sharding_propagation_to_output=*/{false}, /*allow_spmd_sharding_propagation_to_parameters=*/{true, true}) .Run(module.get())); XLA_VLOG_LINES(1, module->ToString()); EXPECT_TRUE(changed); EXPECT_THAT(module->entry_computation()->parameter_instruction(0), op::Sharding("{devices=[4]0,1,2,3}")); EXPECT_THAT(module->entry_computation()->parameter_instruction(1), op::Sharding("{devices=[4]0,1,2,3}")); }
ShardingPropagationTest_ShardAsWithShardBarrier
xla/service/sharding_propagation_test.cc
std::optional<HloSharding> ReturnImprovedSharding( HloSharding sharding, HloInstruction* instruction, bool may_combine_partial_sharding, bool allow_aggressive_resharding = false) { return hlo_sharding_util::ReturnImprovedShardingImpl( std::move(sharding), instruction->has_sharding() ? &instruction->sharding() : nullptr, instruction->shape(), may_combine_partial_sharding, allow_aggressive_resharding); } std::optional<HloSharding> ReturnImprovedSubSharding( HloSharding sharding, HloInstruction* instruction, const ShapeIndex& index, bool may_combine_partial_sharding, bool allow_aggressive_resharding = false) { if (instruction->has_sharding()) { const HloSharding to_improved = instruction->sharding().GetSubSharding(instruction->shape(), index); return hlo_sharding_util::ReturnImprovedShardingImpl( std::move(sharding), &to_improved, ShapeUtil::GetSubshape(instruction->shape(), index), may_combine_partial_sharding, allow_aggressive_resharding); } else { return hlo_sharding_util::ReturnImprovedShardingImpl( std::move(sharding), nullptr, ShapeUtil::GetSubshape(instruction->shape(), index), may_combine_partial_sharding, allow_aggressive_resharding); } } bool MaybeImproveInstructionSharding(HloSharding sharding, HloInstruction* instruction, bool may_combine_partial_sharding, bool allow_aggressive_resharding = false) { if (auto new_sharding = ReturnImprovedSharding( std::move(sharding), instruction, may_combine_partial_sharding, allow_aggressive_resharding)) { instruction->set_sharding(std::move(*new_sharding)); return true; } return false; } bool MaybeImproveInstructionSubSharding( HloSharding sharding, HloInstruction* instruction, const ShapeIndex& index, bool may_combine_partial_sharding, bool allow_aggressive_resharding = false) { if (instruction->shape().IsTuple()) { if (auto new_sub_sharding = ReturnImprovedSubSharding( std::move(sharding), instruction, index, may_combine_partial_sharding, allow_aggressive_resharding)) { HloSharding new_sharding = instruction->has_sharding() ? instruction->sharding() : HloSharding::Single(instruction->shape(), HloSharding::Replicate()); ShapeTree<HloSharding> sharding_shape_tree = new_sharding.GetAsShapeTree(instruction->shape()); *sharding_shape_tree.mutable_element(index) = new_sub_sharding.value(); instruction->set_sharding(HloSharding::Tuple(sharding_shape_tree)); return true; } else { return false; } } CHECK(index.size() == 1 && index[0] == 0); return MaybeImproveInstructionSharding(std::move(sharding), instruction, may_combine_partial_sharding, allow_aggressive_resharding); } bool IsConvolutionKernelSmall(const HloInstruction* instruction) { CHECK_EQ(instruction->opcode(), HloOpcode::kConvolution); const HloInstruction* rhs = instruction->operand(1); const auto& dnums = instruction->convolution_dimension_numbers(); int64_t kernel_dim_prod = 1; int64_t output_dim_prod = 1; for (int64_t i = 0; i < dnums.input_spatial_dimensions().size(); ++i) { int64_t kernel_dim = rhs->shape().dimensions(dnums.kernel_spatial_dimensions(i)); kernel_dim_prod *= kernel_dim; int64_t output_dim = instruction->shape().dimensions(dnums.output_spatial_dimensions(i)); output_dim_prod *= output_dim; if (kernel_dim >= output_dim && (i < 2 || kernel_dim > 3 || kernel_dim_prod >= output_dim_prod)) { return false; } } return true; } bool IsPassthroughCustomOps(const HloInstruction* hlo) { if (hlo->IsCustomCall({"Sharding", "X64Combine", "LayoutConstraint"})) { return true; } if (hlo->operand_count() != 1 || !hlo->shape().IsArray() || !hlo->operand(0)->shape().IsArray() || hlo->operand(0)->shape().rank() != hlo->shape().rank()) { return false; } return hlo->IsCustomCall( {"ResizeNearest", "ResizeBilinear", "ResizeNearestGrad", "ResizeBilinearGrad", "Cholesky", host_memory_offload_annotations::kMoveToDeviceCustomCallTarget, host_memory_offload_annotations::kMoveToHostCustomCallTarget}); } const HloInstruction* PickRepresentativeOperand( const HloInstruction* instruction) { switch (instruction->opcode()) { case HloOpcode::kMap: case HloOpcode::kPad: case HloOpcode::kPower: case HloOpcode::kOptimizationBarrier: case HloOpcode::kReverse: case HloOpcode::kSlice: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: // For these opcodes the output sharding has to be determined by the // sharding of the first operand but we can only determine sharding based // on it if it already has a sharding. if (instruction->operand(0)->has_sharding()) { return instruction->operand(0); } return nullptr; case HloOpcode::kAbs: case HloOpcode::kAdd: case HloOpcode::kAnd: case HloOpcode::kAtan2: case HloOpcode::kBitcastConvert: case HloOpcode::kCeil: case HloOpcode::kClamp: case HloOpcode::kClz: case HloOpcode::kCompare: case HloOpcode::kComplex: case HloOpcode::kConcatenate: case HloOpcode::kConvert: case HloOpcode::kCopy: case HloOpcode::kCos: case HloOpcode::kAllGather: case HloOpcode::kAllReduce: case HloOpcode::kReduceScatter: case HloOpcode::kAllToAll: case HloOpcode::kCollectiveBroadcast: case HloOpcode::kCollectivePermute: case HloOpcode::kDivide: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kFloor: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kMultiply: case HloOpcode::kNegate: case HloOpcode::kNot: case HloOpcode::kOr: case HloOpcode::kPopulationCount: case HloOpcode::kReal: case HloOpcode::kReducePrecision: case HloOpcode::kRemainder: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kRsqrt: case HloOpcode::kSelect: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kTopK: case HloOpcode::kSort: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kSubtract: case HloOpcode::kStochasticConvert: case HloOpcode::kTan: case HloOpcode::kTanh: case HloOpcode::kWhile: case HloOpcode::kXor: { // For these opcodes the output sharding can be determined by any operand // so we find the operand with the most specific sharding. const HloInstruction* best_operand = nullptr; for (const HloInstruction* operand : instruction->operands()) { if (operand->has_sharding() && (best_operand == nullptr || hlo_sharding_util::IsShardingMoreSpecific( operand->sharding(), best_operand->sharding()))) { best_operand = operand; } } return best_operand; } case HloOpcode::kCustomCall: { if (IsPassthroughCustomOps(instruction)) { return instruction->operand(0); } return nullptr; } // There is no suitable operand for the rest of the opcodes. case HloOpcode::kAddDependency: case HloOpcode::kAfterAll: case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: case HloOpcode::kAllGatherStart: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduceStart: case HloOpcode::kAllReduceDone: case HloOpcode::kBatchNormGrad: case HloOpcode::kBatchNormInference: case HloOpcode::kBatchNormTraining: case HloOpcode::kBitcast: case HloOpcode::kBroadcast: case HloOpcode::kCall: case HloOpcode::kCholesky: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCollectivePermuteStart: case HloOpcode::kConditional: case HloOpcode::kConstant: case HloOpcode::kConvolution: case HloOpcode::kCopyDone: case HloOpcode::kCopyStart: case HloOpcode::kDomain: case HloOpcode::kDot: case HloOpcode::kDynamicSlice: case HloOpcode::kDynamicUpdateSlice: case HloOpcode::kDynamicReshape: case HloOpcode::kFft: case HloOpcode::kFusion: case HloOpcode::kGather: case HloOpcode::kGetTupleElement: case HloOpcode::kInfeed: case HloOpcode::kIota: case HloOpcode::kOutfeed: case HloOpcode::kParameter: case HloOpcode::kPartitionId: case HloOpcode::kRecv: case HloOpcode::kRecvDone: case HloOpcode::kReduce: case HloOpcode::kReduceWindow: case HloOpcode::kReplicaId: case HloOpcode::kReshape: case HloOpcode::kRng: case HloOpcode::kRngGetAndUpdateState: case HloOpcode::kRngBitGenerator: case HloOpcode::kScatter: case HloOpcode::kSelectAndScatter: case HloOpcode::kSend: case HloOpcode::kSendDone: case HloOpcode::kTranspose: case HloOpcode::kTriangularSolve: case HloOpcode::kTuple: case HloOpcode::kGetDimensionSize: case HloOpcode::kSetDimensionSize: return nullptr; } } bool SupportSpatialPartitioning( const HloInstruction* instruction, const ShardingPropagation::ComputationMap& computation_map, bool is_spmd, bool allow_spmd_sharding_propagation_to_output, bool allow_spmd_sharding_propagation_to_parameters, const CustomCallShardingHelper* sharding_helper) { const bool is_entry_root = instruction->parent() ->parent() ->entry_computation() ->root_instruction() == instruction; if (instruction->parent()->root_instruction() == instruction && computation_map.find(instruction->parent()) == computation_map.end() && !(is_entry_root && allow_spmd_sharding_propagation_to_output)) { // We don't support sharding the root instruction of a computation yet, // unless the computation is a while body. return false; } if (instruction->IsElementwise() && (instruction->opcode() != HloOpcode::kRng || is_spmd)) { return true; } switch (instruction->opcode()) { case HloOpcode::kBroadcast: case HloOpcode::kConcatenate: case HloOpcode::kConditional: case HloOpcode::kConstant: case HloOpcode::kConvolution: case HloOpcode::kOptimizationBarrier: case HloOpcode::kDot: case HloOpcode::kDynamicSlice: case HloOpcode::kDynamicUpdateSlice: case HloOpcode::kGather: case HloOpcode::kGetTupleElement: case HloOpcode::kInfeed: case HloOpcode::kIota: case HloOpcode::kPad: case HloOpcode::kReduceWindow: case HloOpcode::kReshape: case HloOpcode::kScatter: case HloOpcode::kSelectAndScatter: case HloOpcode::kSlice: case HloOpcode::kSort: case HloOpcode::kTranspose: case HloOpcode::kTuple: case HloOpcode::kWhile: case HloOpcode::kReduce: case HloOpcode::kRngBitGenerator: case HloOpcode::kAllReduce: case HloOpcode::kReduceScatter: return true; case HloOpcode::kParameter: return allow_spmd_sharding_propagation_to_parameters || computation_map.find(instruction->parent()) != computation_map.end(); case HloOpcode::kReverse: return is_spmd; case HloOpcode::kCustomCall: if (!is_spmd) { return false; } if (auto* partitioner = GetCustomCallPartitioner(instruction->custom_call_target())) { return partitioner->IsCustomCallShardable(instruction); } return (IsPassthroughCustomOps(instruction) || sharding_helper->IsCustomCallShardable(instruction)); default: return false; } } std::optional<HloSharding> LookaheadUserSharding(HloInstruction* instr, bool is_spmd, const CallGraph& call_graph) { if (instr->user_count() != 1) { return std::nullopt; } HloInstruction* current_user = instr->users()[0]; std::optional<HloSharding> sharding; std::vector<HloInstruction*> users_chain = {instr, current_user}; // Collect single user instructions along the way. while (!current_user->has_sharding()) { // Only consider single user chains. if (current_user->users().size() != 1) { users_chain.clear(); break; } current_user = current_user->users()[0]; users_chain.push_back(current_user); } // Early exit for unsupported cases. if (users_chain.empty()) { return std::nullopt; } for (int i = users_chain.size() - 1; i >= 1; --i) { HloInstruction* user = users_chain[i]; HloInstruction* current = users_chain[i - 1]; CHECK(user->has_sharding()); sharding = ShardingPropagation::GetShardingFromUser( *current, *user, INT64_MAX, is_spmd, call_graph, /*sharding_helper=*/nullptr); // We need to set the sharding to the instruction, because // GetShardingFromUser() interface uses sharding from the instruction // itself. It will be cleared out later. if (sharding.has_value() && i != 1) { current->set_sharding(*sharding); continue; } break; } // Clear the sharding of the middle instructions we set the sharding of // because they were unsharded. for (int i = 1; i < users_chain.size() - 1; ++i) { users_chain[i]->clear_sharding(); } return sharding; } bool InferGatherParallelShardingFromOperands( HloInstruction* instruction, const hlo_sharding_util::GatherScatterParallelDims& parallel_dims, bool may_combine_partial_sharding) { CHECK(DynCast<HloGatherInstruction>(instruction)); bool changed = false; auto aligned_operand_parallel_dims = hlo_sharding_util::IndexAlignedOperandParallelDims(parallel_dims); auto output_parallel_dims = hlo_sharding_util::GetGatherParallelOutputDims( *instruction, parallel_dims); // Infer output sharding from scatter operand sharding. if (hlo_sharding_util::IsSpatiallyPartitioned(instruction->operand(0))) { changed |= MaybeImproveInstructionSharding( hlo_sharding_util:: InferGatherScatterParallelShardingFromOperandSharding( instruction->operand(0)->sharding(), instruction->operand(0)->shape(), instruction->shape(), absl::MakeConstSpan(aligned_operand_parallel_dims), absl::MakeConstSpan(output_parallel_dims)), instruction, may_combine_partial_sharding); } // Infer output sharding from scatter indices sharding. if (hlo_sharding_util::IsSpatiallyPartitioned(instruction->operand(1))) { changed |= MaybeImproveInstructionSharding( hlo_sharding_util:: InferGatherScatterParallelShardingFromOperandSharding( instruction->operand(1)->sharding(), instruction->operand(1)->shape(), instruction->shape(), absl::MakeConstSpan(parallel_dims.indices_parallel_dims), absl::MakeConstSpan(output_parallel_dims)), instruction, may_combine_partial_sharding); } return changed; } bool InferScatterParallelShardingFromOperands( HloInstruction* instruction, const hlo_sharding_util::GatherScatterParallelDims& parallel_dims, bool may_combine_partial_sharding) { HloScatterInstruction* scatter = DynCast<HloScatterInstruction>(instruction); CHECK(scatter); const int64_t operand_count = scatter->scatter_operand_count(); auto scatter_operands = scatter->scatter_operands(); auto scatter_indices = scatter->scatter_indices(); auto scatter_updates = scatter->scatter_updates(); bool changed = false; auto aligned_operand_parallel_dims = hlo_sharding_util::IndexAlignedOperandParallelDims(parallel_dims); auto update_parallel_dims = hlo_sharding_util::GetScatterParallelUpdateDims( *instruction, parallel_dims); auto output_parallel_dims = aligned_operand_parallel_dims; // Infer output sharding from scatter operand sharding. Shape shape = operand_count == 1 ? instruction->shape() : ShapeUtil::GetSubshape(instruction->shape(), {0}); for (int64_t i = 0; i != operand_count; ++i) { if (hlo_sharding_util::IsSpatiallyPartitioned(scatter_operands[i])) { changed |= MaybeImproveInstructionSubSharding( hlo_sharding_util:: InferGatherScatterParallelShardingFromOperandSharding( scatter_operands[i]->sharding(), scatter_operands[i]->shape(), shape, absl::MakeConstSpan(aligned_operand_parallel_dims), absl::MakeConstSpan(output_parallel_dims)), instruction, {i}, may_combine_partial_sharding); } } // Infer output sharding from scatter indices sharding. if (hlo_sharding_util::IsSpatiallyPartitioned(scatter_indices)) { auto parallel_sharding_from_indices = hlo_sharding_util:: InferGatherScatterParallelShardingFromOperandSharding( scatter_indices->sharding(), scatter_indices->shape(), shape, absl::MakeConstSpan(parallel_dims.indices_parallel_dims), absl::MakeConstSpan(output_parallel_dims)); for (int64_t i = 0; i != operand_count; ++i) { changed |= MaybeImproveInstructionSubSharding( parallel_sharding_from_indices, instruction, {i}, may_combine_partial_sharding); } } // Infer output sharding from scatter update sharding. for (int64_t i = 0; i != operand_count; ++i) { if (hlo_sharding_util::IsSpatiallyPartitioned(scatter_updates[i])) { changed |= MaybeImproveInstructionSubSharding( hlo_sharding_util:: InferGatherScatterParallelShardingFromOperandSharding( scatter_updates[i]->sharding(), scatter_updates[i]->shape(), shape, absl::MakeConstSpan(update_parallel_dims), absl::MakeConstSpan(output_parallel_dims)), instruction, {i}, may_combine_partial_sharding); } } return changed; } bool CanPropagateThroughAtAggressiveLevel(const HloInstruction& inst, int64_t aggressiveness) { // At minimum aggressiveness, only allow pass-through ops. if (aggressiveness < 1 && !(inst.IsElementwise() || inst.IsCustomCall("Sharding")) && inst.opcode() != HloOpcode::kTranspose && inst.opcode() != HloOpcode::kReshape && inst.opcode() != HloOpcode::kTuple && inst.opcode() != HloOpcode::kGetTupleElement && inst.opcode() != HloOpcode::kWhile && inst.opcode() != HloOpcode::kDynamicSlice && inst.opcode() != HloOpcode::kDynamicUpdateSlice && inst.opcode() != HloOpcode::kOptimizationBarrier && inst.opcode() != HloOpcode::kConcatenate && inst.opcode() != HloOpcode::kCall && inst.opcode() != HloOpcode::kCopy) { return false; } // Broadcast propagation should have at least aggressiveness 2. if (aggressiveness < 2 && inst.opcode() == HloOpcode::kBroadcast) { return false; } return true; } bool SameShardingMetadata(const HloSharding& a, const HloSharding& b) { DCHECK_EQ(a, b); auto same_metadata = [](absl::Span<const OpMetadata> a, absl::Span<const OpMetadata> b) { if (a.size() != b.size()) return false; for (int i = 0, e = a.size(); i < e; ++i) { if (!protobuf_util::ProtobufEquals(a[i], b[i])) { return false; } } return true; }; if (a.IsTuple()) { for (int i = 0, e = a.tuple_elements().size(); i < e; ++i) { if (!same_metadata(a.tuple_elements()[i].metadata(), b.tuple_elements()[i].metadata())) { return false; } } return true; } else { return same_metadata(a.metadata(), b.metadata()); } } auto same_metadata = [](absl::Span<const OpMetadata> a, absl::Span<const OpMetadata> b) { if (a.size() != b.size()) return false; for (int i = 0, e = a.size(); i < e; ++i) { if (!protobuf_util::ProtobufEquals(a[i], b[i])) { return false; } } return true; }; bool AssignShardingMetadata( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { bool changed = false; for (HloComputation* computation : module->computations(execution_threads)) { for (HloInstruction* instruction : computation->instructions()) { const auto& metadata = instruction->metadata(); if (!instruction->has_sharding() || metadata.ByteSizeLong() == 0) { continue; } HloSharding sharding_with_metadata = instruction->sharding().WithMetadata({metadata}, /*overwrite=*/false); if (!SameShardingMetadata(instruction->sharding(), sharding_with_metadata)) { instruction->set_sharding(std::move(sharding_with_metadata)); changed = true; } } } return changed; } bool RemoveShardingMetadata( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { bool changed = false; for (HloComputation* computation : module->computations(execution_threads)) { for (HloInstruction* instruction : computation->instructions()) { if (!instruction->has_sharding()) { continue; } HloSharding sharding_no_metadata = instruction->sharding().WithoutMetadata(); if (!SameShardingMetadata(instruction->sharding(), sharding_no_metadata)) { instruction->set_sharding(std::move(sharding_no_metadata)); changed = true; } } } return changed; } absl::Status CheckAndUpdateDeviceAssignmentsInWhileBody( HloInstruction* while_instruction) { auto bad_status = [](HloInstruction* instruction, int64_t device, HloInstruction* channel_instruction, int64_t correct_device) { return FailedPrecondition( "Instruction: %s is on device: %d, which conflicts with device: %d " "of channel instruction: %s", instruction->name(), device, correct_device, channel_instruction->name()); }; CHECK_EQ(while_instruction->opcode(), HloOpcode::kWhile); HloComputation* while_body = while_instruction->while_body(); // Maps a device number to an instruction in the while_body with that // device assignment. std::map<int64_t, HloInstruction*> devices_to_instructions; std::optional<int64_t> unique_device = std::nullopt; HloInstruction* channel_instruction = nullptr; for (HloInstruction* instruction : while_body->instructions()) { if (instruction->sharding_unique_device()) { auto opcode = instruction->opcode(); int64_t device = *instruction->sharding_unique_device(); if (unique_device.has_value()) { if (*unique_device != device) { return bad_status(instruction, device, channel_instruction, *unique_device); } } else if (((opcode == HloOpcode::kSend || opcode == HloOpcode::kRecv) && !Cast<HloSendRecvInstruction>(instruction) ->is_host_transfer()) // Cross-replica AllReduces don't have a channel_id, and we // don't enforce any invariant about their device assignment. || ((opcode == HloOpcode::kAllReduce || opcode == HloOpcode::kReduceScatter) && instruction->channel_id())) { channel_instruction = instruction; unique_device = device; if (!devices_to_instructions.empty()) { for (auto it = devices_to_instructions.begin(); it != devices_to_instructions.end(); ++it) { if (*unique_device != it->first) { return bad_status(it->second, it->first, channel_instruction, *unique_device); } } } } else { devices_to_instructions[device] = instruction; } } } if (unique_device.has_value()) { auto while_device = while_instruction->sharding_unique_device(); if (while_device.has_value() && *unique_device != *while_device) { return bad_status(while_instruction, *while_device, channel_instruction, *unique_device); } auto body_root = while_body->root_instruction(); auto root_device = body_root->sharding_unique_device(); if (!root_device.has_value()) { body_root->set_device_sharding(*unique_device); } else if (*unique_device != *root_device) { return bad_status(body_root, *root_device, channel_instruction, *unique_device); } } return absl::OkStatus(); } auto bad_status = [](HloInstruction* instruction, int64_t device, HloInstruction* channel_instruction, int64_t correct_device) { return FailedPrecondition( "Instruction: %s is on device: %d, which conflicts with device: %d " "of channel instruction: %s", instruction->name(), device, correct_device, channel_instruction->name()); }; bool RefineManualAutoShardingFromAuto( const HloSharding& to_merge, absl::Span<const int64_t> unspecified_dims, HloSharding* auto_sharding, HloSharding* manual_sharding) { if (!manual_sharding->IsManualSubgroup() || auto_sharding->IsManualSubgroup() || !manual_sharding->HasPartialReplication() || manual_sharding->subgroup_types().size() != 2) { // We do not support nested subgroup manual. man_conversion_op must have // replication in order to be merged. return false; } HloSharding partial_rep = hlo_sharding_util::PartiallyReplicateTiledShardingOnAllDimsExcept( to_merge, unspecified_dims); if (partial_rep.IsTileMaximal()) { return false; } // Merge with the non-manual partial annotation. if (!hlo_sharding_util::MergeShardingIfCompatible( partial_rep, auto_sharding->NumTiles() + 1, auto_sharding)) { return false; } // Merge with the manual partial annotation. const int64_t data_rank = partial_rep.TiledDataRank(); // We are also merging the non-manual sharding into the manual sharding. To // leverage existing merging implementation, we treat the manual dim as a // data dim, and add it right before the replication dim. std::vector<int64_t> partial_manual_shape( partial_rep.tile_assignment().dimensions().begin(), partial_rep.tile_assignment().dimensions().end()); partial_manual_shape.insert(partial_manual_shape.begin() + data_rank, 1); auto partial_tiling_for_manual = partial_rep.tile_assignment().Reshape(partial_manual_shape); HloSharding partial_rep_for_manual = HloSharding::PartialTile( partial_tiling_for_manual, partial_rep.metadata()); auto man_tiling = manual_sharding->tile_assignment(); if (manual_sharding->subgroup_types().back() != OpSharding::REPLICATED) { // Move the manual dim before replication dim. std::vector<int> transposed_dims(man_tiling.num_dimensions()); absl::c_iota(transposed_dims, 0); std::swap(transposed_dims.back(), transposed_dims[data_rank]); man_tiling = man_tiling.Transpose(transposed_dims); } HloSharding tmp_sharding_for_merging = HloSharding::PartialTile( std::move(man_tiling), manual_sharding->metadata()); if (!hlo_sharding_util::MergeShardingIfCompatible( partial_rep_for_manual, tmp_sharding_for_merging.NumTiles() + 1, &tmp_sharding_for_merging)) { return false; } std::vector<OpSharding::Type> subgroup_types; subgroup_types.push_back(OpSharding::MANUAL); if (tmp_sharding_for_merging.HasPartialReplication()) { subgroup_types.push_back(OpSharding::REPLICATED); } *manual_sharding = HloSharding::Subgroup( tmp_sharding_for_merging.tile_assignment(), subgroup_types, tmp_sharding_for_merging.metadata()); return true; } bool RefineManualAutoShardingFromManual( const HloSharding& to_merge, absl::Span<const int64_t> unspecified_dims, HloSharding* auto_sharding, HloSharding* manual_sharding) { if (!to_merge.IsManualSubgroup() || !manual_sharding->IsManualSubgroup() || !manual_sharding->HasPartialReplication() || auto_sharding->IsManualSubgroup() || manual_sharding->subgroup_types().size() != 2) { return false; } HloSharding partial_rep = hlo_sharding_util::PartiallyReplicateTiledShardingOnAllDimsExcept( to_merge, unspecified_dims); if (partial_rep.IsTileMaximal()) { return false; } if (!hlo_sharding_util::MergeShardingIfCompatible( partial_rep, manual_sharding->NumTiles() + 1, manual_sharding)) { return false; } HloSharding partial_rep_for_auto = HloSharding::Subgroup( partial_rep.tile_assignment(), std::vector<OpSharding::Type>(partial_rep.subgroup_types().size(), OpSharding::REPLICATED), partial_rep.metadata()); if (!hlo_sharding_util::MergeShardingIfCompatible( partial_rep_for_auto, auto_sharding->NumTiles() + 1, auto_sharding)) { return false; } return true; } bool InferUnspecifiedDimsFromOperand(HloInstruction* annotate_op, absl::Span<const int64_t> unspecified_dims, HloInstruction** man_conversion_op_after) { // ProcessShardingInstruction will either keep the "Sharding" custom call as // is or replace it with a copy. CHECK(annotate_op->IsCustomCall("Sharding") || annotate_op->opcode() == HloOpcode::kCopy); if (!hlo_sharding_util::IsSpatiallyPartitioned(annotate_op->operand(0))) { return false; } const HloSharding& operand_sharding = annotate_op->operand(0)->sharding(); if (!operand_sharding.IsTiled()) { return false; } HloInstruction* man_conversion_op = nullptr; if (annotate_op->user_count() == 1) { HloInstruction* user = annotate_op->users()[0]; if (user->IsCustomCall("SPMDFullToShardShape") || user->IsCustomCall("SPMDShardToFullShape")) { std::vector<int64_t> user_unspec_dims; if (!sharding_op_util::ParseAttributes( Cast<HloCustomCallInstruction>(user)->opaque(), &user_unspec_dims) .ok()) { return false; } absl::c_sort(user_unspec_dims); if (unspecified_dims != user_unspec_dims) { // The manual/auto conversion op must have the same set of unspecified // dims. return false; } man_conversion_op = user; } } *man_conversion_op_after = man_conversion_op; if (man_conversion_op == nullptr) { HloSharding partial_replicated = hlo_sharding_util::PartiallyReplicateTiledShardingOnAllDimsExcept( operand_sharding, unspecified_dims); HloSharding sharding = annotate_op->sharding(); if (!hlo_sharding_util::MergeShardingIfCompatible( partial_replicated, sharding.NumTiles() + 1, &sharding)) { return false; } annotate_op->set_sharding(sharding); return true; } if (man_conversion_op->IsCustomCall("SPMDFullToShardShape")) { HloSharding auto_sharding = annotate_op->sharding(); HloSharding manual_sharding = man_conversion_op->sharding(); if (!RefineManualAutoShardingFromAuto(operand_sharding, unspecified_dims, &auto_sharding, &manual_sharding)) { return false; } annotate_op->set_sharding(auto_sharding); man_conversion_op->set_sharding(manual_sharding); return true; } CHECK(man_conversion_op->IsCustomCall("SPMDShardToFullShape")); HloSharding manual_sharding = annotate_op->sharding(); HloSharding auto_sharding = man_conversion_op->sharding(); if (!RefineManualAutoShardingFromManual(operand_sharding, unspecified_dims, &auto_sharding, &manual_sharding)) { return false; } annotate_op->set_sharding(manual_sharding); man_conversion_op->set_sharding(auto_sharding); return true; } bool InferUnspecifiedDimsFromOneUser(HloInstruction* annotate_op, const HloInstruction* user, int64_t aggressiveness, bool is_spmd, absl::Span<const int64_t> unspecified_dims, HloInstruction* man_conversion_op, const CallGraph& call_graph) { CHECK(annotate_op->IsCustomCall("Sharding") || annotate_op->opcode() == HloOpcode::kCopy); if (!user->has_sharding() || !user->sharding().IsTiled()) { return false; } std::optional<HloSharding> user_sharding = ShardingPropagation::GetShardingFromUser( man_conversion_op == nullptr ? *annotate_op : *man_conversion_op, *user, aggressiveness, is_spmd, call_graph, /*sharding_helper=*/nullptr); if (!user_sharding.has_value() || user_sharding->IsTileMaximal()) { return false; } if (man_conversion_op == nullptr) { HloSharding partial_replicated = hlo_sharding_util::PartiallyReplicateTiledShardingOnAllDimsExcept( *user_sharding, unspecified_dims); HloSharding sharding = annotate_op->sharding(); if (!hlo_sharding_util::MergeShardingIfCompatible( partial_replicated, sharding.NumTiles() + 1, &sharding)) { return false; } annotate_op->set_sharding(sharding); return true; } if (man_conversion_op->IsCustomCall("SPMDFullToShardShape")) { HloSharding auto_sharding = annotate_op->sharding(); HloSharding manual_sharding = man_conversion_op->sharding(); if (!RefineManualAutoShardingFromManual(*user_sharding, unspecified_dims, &auto_sharding, &manual_sharding)) { return false; } annotate_op->set_sharding(auto_sharding); man_conversion_op->set_sharding(manual_sharding); return true; } CHECK(man_conversion_op->IsCustomCall("SPMDShardToFullShape")); HloSharding manual_sharding = annotate_op->sharding(); HloSharding auto_sharding = man_conversion_op->sharding(); if (!RefineManualAutoShardingFromAuto(*user_sharding, unspecified_dims, &auto_sharding, &manual_sharding)) { return false; } annotate_op->set_sharding(manual_sharding); man_conversion_op->set_sharding(auto_sharding); return true; } bool InferUnspecifiedDimsFromUsers(HloInstruction* annotate_op, absl::Span<const int64_t> unspecified_dims, int64_t aggressiveness, bool is_spmd, HloInstruction** man_conversion_op_after, const CallGraph& call_graph) { HloInstruction* man_conversion_op = nullptr; if (annotate_op->user_count() == 1) { HloInstruction* user = annotate_op->users()[0]; if (user->IsCustomCall("SPMDFullToShardShape") || user->IsCustomCall("SPMDShardToFullShape")) { std::vector<int64_t> user_unspec_dims; absl::c_sort(user_unspec_dims); if (!sharding_op_util::ParseAttributes( Cast<HloCustomCallInstruction>(user)->opaque(), &user_unspec_dims) .ok() || unspecified_dims != user_unspec_dims) { // The manual/auto conversion op must have the same set of unspecified // dims. return false; } man_conversion_op = user; } } *man_conversion_op_after = man_conversion_op; HloInstruction* op_for_users = man_conversion_op == nullptr ? annotate_op : man_conversion_op; bool changed = false; for (HloInstruction* user : op_for_users->users()) { changed |= InferUnspecifiedDimsFromOneUser( annotate_op, user, aggressiveness, is_spmd, unspecified_dims, man_conversion_op, call_graph); } return changed; } bool InferUnspecifiedDimsFromShardGroup( HloInstruction* annotate_op, absl::Span<const int64_t> unspecified_dims, const absl::flat_hash_set<HloInstruction*>& shard_group) { // ProcessShardingInstruction will either keep the "Sharding" custom call as // is or replace it with a copy. CHECK(annotate_op->IsCustomCall("Sharding") || annotate_op->opcode() == HloOpcode::kCopy); // Do not propagate sharding to ShardBarrierTo custom-call. if (annotate_op->IsCustomCall(spmd::kShardBarrierTo)) { return false; } bool changed = false; for (const HloInstruction* member : shard_group) { if (member == annotate_op) { continue; } // Do not propagate sharding from ShardBarrierFrom custom-call. if (member->IsCustomCall(spmd::kShardBarrierFrom)) { continue; } if (!hlo_sharding_util::IsSpatiallyPartitioned(member)) { continue; } const HloSharding& member_sharding = member->sharding(); if (!member_sharding.IsTiled()) { continue; } HloSharding partial_replicated = hlo_sharding_util::PartiallyReplicateTiledShardingOnAllDimsExcept( member_sharding, unspecified_dims); HloSharding sharding = annotate_op->sharding(); if (!hlo_sharding_util::MergeShardingIfCompatible( partial_replicated, sharding.NumTiles() + 1, &sharding)) { continue; } annotate_op->set_sharding(sharding); changed |= true; } return changed; } bool IsCSEPreventionTarget(const HloInstruction* instruction) { // Scalar broadcasts are the most common CSE target that causes cross-layer // propagation on unrelated subgraphs. return instruction->opcode() == HloOpcode::kBroadcast && instruction->operand(0)->shape().rank() == 0; } HloSharding SetCSEPreventionSharding(const HloSharding& sharding) { OpMetadata metadata; metadata.set_op_name("_sharding_propagation_cse_prevention"); return sharding.WithMetadata({metadata}, /*overwrite=*/true); } bool IsCSEPreventionSharding(const HloSharding& sharding) { if (sharding.metadata().size() != 1) { return false; } return sharding.metadata()[0].op_name() == "_sharding_propagation_cse_prevention"; } bool InferDotShardingFromOperands( HloInstruction* instruction, const CallGraph& call_graph, const dot_as_convolution_util::DotConvolutionDimsInfo& dnums, bool may_combine_partial_sharding, bool is_spmd) { auto from_operand = [&](int64_t operand_index) { auto operand = instruction->operand(operand_index); const HloSharding& operand_sharding = operand->sharding(); if (operand_sharding.IsTileMaximal()) { return operand_sharding; } std::vector<int64_t> contracting_dims; contracting_dims.reserve(dnums.contracting_dims.size()); for (const auto& dim : dnums.contracting_dims) { contracting_dims.push_back(operand_index == 0 ? dim.lhs : dim.rhs); } // It's possible that some size-1 spatial dims of convolutions are parsed as // non-contracting dims. We might have tiled dimensions on them. for (const auto& dim : operand_index == 0 ? dnums.rhs_non_contracting_dims : dnums.lhs_non_contracting_dims) { int64_t d = operand_index == 0 ? dim.lhs : dim.rhs; if (d >= 0) { contracting_dims.push_back(d); } } auto replicate_contracting_dims = hlo_sharding_util::PartiallyReplicateTiledShardingOnDims( operand_sharding, contracting_dims); std::vector<int64_t> out_dims_to_op_perm(instruction->shape().rank(), -1); std::vector<int64_t> op_dims_to_output_perm(operand->shape().rank(), -1); for (const auto& dim : dnums.batch_dims) { out_dims_to_op_perm[dim.output] = operand_index == 0 ? dim.lhs : dim.rhs; op_dims_to_output_perm[operand_index == 0 ? dim.lhs : dim.rhs] = dim.output; } for (const auto& dim : operand_index == 0 ? dnums.lhs_non_contracting_dims : dnums.rhs_non_contracting_dims) { out_dims_to_op_perm[dim.output] = operand_index == 0 ? dim.lhs : dim.rhs; op_dims_to_output_perm[operand_index == 0 ? dim.lhs : dim.rhs] = dim.output; } return *hlo_sharding_util::TransposeShardingWithCollapsedDims( replicate_contracting_dims, op_dims_to_output_perm, out_dims_to_op_perm); }; std::optional<HloSharding> improved_operand_0; std::optional<HloSharding> improved_operand_1; if (hlo_sharding_util::IsSpatiallyPartitioned(instruction->operand(0))) { improved_operand_0 = ReturnImprovedSharding( from_operand(0), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/false); } if (hlo_sharding_util::IsSpatiallyPartitioned(instruction->operand(1))) { improved_operand_1 = ReturnImprovedSharding( from_operand(1), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/false); } // If not improved sharding found then do not set any sharding. if (!improved_operand_0.has_value() && !improved_operand_1.has_value()) { return false; } // Sharding found from operand 0 but not operand 1. Set sharding from operand // 0 if (improved_operand_0.has_value() && !improved_operand_1.has_value()) { instruction->set_sharding(*improved_operand_0); return true; } // Sharding found from operand 1 but not operand 0. Set sharding from operand // 1 if (!improved_operand_0.has_value() && improved_operand_1.has_value()) { instruction->set_sharding(*improved_operand_1); return true; } CHECK(improved_operand_0.has_value() && improved_operand_1.has_value()); std::optional<HloSharding> lookahead_sharding = LookaheadUserSharding(instruction, is_spmd, call_graph); std::array<HloSharding, 2> sharding_priority = {*improved_operand_0, *improved_operand_1}; bool priority_defined_with_lookahead = false; // Found sharding from lookahead. if (lookahead_sharding.has_value()) { const bool operand_0_is_lookahead_subtiling = hlo_sharding_util::IsSubTilingOrEqualSharding( instruction->shape(), *lookahead_sharding, *improved_operand_0); const bool operand_1_is_lookahead_subtiling = hlo_sharding_util::IsSubTilingOrEqualSharding( instruction->shape(), *lookahead_sharding, *improved_operand_1); // If the sharding from operand 0 is a subtiling of the user, but not the // one from operand 1 prioritize that sharding. if (operand_0_is_lookahead_subtiling && !operand_1_is_lookahead_subtiling) { priority_defined_with_lookahead = true; } // If the sharding from operand 1 is a subtiling of the user, but not the // one from operand 0 prioritize that sharding. if (!operand_0_is_lookahead_subtiling && operand_1_is_lookahead_subtiling) { instruction->set_sharding(*improved_operand_1); std::swap(sharding_priority[0], sharding_priority[1]); priority_defined_with_lookahead = true; } } // If lookahead didn't define a priority then use size. if (!priority_defined_with_lookahead && ShapeUtil::ByteSizeOf(instruction->operand(0)->shape()) < ShapeUtil::ByteSizeOf(instruction->operand(1)->shape())) { std::swap(sharding_priority[0], sharding_priority[1]); } // Set primary sharding to the instruction and then try to improve it with // the secondary sharding. instruction->set_sharding(sharding_priority[0]); MaybeImproveInstructionSharding(sharding_priority[1], instruction, may_combine_partial_sharding); return true; } auto from_operand = [&](int64_t operand_index) { auto operand = instruction->operand(operand_index); const HloSharding& operand_sharding = operand->sharding(); if (operand_sharding.IsTileMaximal()) { return operand_sharding; } std::vector<int64_t> contracting_dims; contracting_dims.reserve(dnums.contracting_dims.size()); for (const auto& dim : dnums.contracting_dims) { contracting_dims.push_back(operand_index == 0 ? dim.lhs : dim.rhs); } // It's possible that some size-1 spatial dims of convolutions are parsed as // non-contracting dims. We might have tiled dimensions on them. for (const auto& dim : operand_index == 0 ? dnums.rhs_non_contracting_dims : dnums.lhs_non_contracting_dims) { int64_t d = operand_index == 0 ? dim.lhs : dim.rhs; if (d >= 0) { contracting_dims.push_back(d); } } auto replicate_contracting_dims = hlo_sharding_util::PartiallyReplicateTiledShardingOnDims( operand_sharding, contracting_dims); std::vector<int64_t> out_dims_to_op_perm(instruction->shape().rank(), -1); std::vector<int64_t> op_dims_to_output_perm(operand->shape().rank(), -1); for (const auto& dim : dnums.batch_dims) { out_dims_to_op_perm[dim.output] = operand_index == 0 ? dim.lhs : dim.rhs; op_dims_to_output_perm[operand_index == 0 ? dim.lhs : dim.rhs] = dim.output; } for (const auto& dim : operand_index == 0 ? dnums.lhs_non_contracting_dims : dnums.rhs_non_contracting_dims) { out_dims_to_op_perm[dim.output] = operand_index == 0 ? dim.lhs : dim.rhs; op_dims_to_output_perm[operand_index == 0 ? dim.lhs : dim.rhs] = dim.output; } return *hlo_sharding_util::TransposeShardingWithCollapsedDims( replicate_contracting_dims, op_dims_to_output_perm, out_dims_to_op_perm); }; bool InferConvolutionShardingFromOperands(HloInstruction* instruction, const CallGraph& call_graph, int64_t aggressiveness, bool may_combine_partial_sharding, bool is_spmd) { auto get_partitions_for_dims = [&](const HloInstruction* inst, absl::Span< const dot_as_convolution_util::DotConvolutionDimsInfo::DimNums> dims, int lhs_or_rhs) { int64_t partitions = 1; if (!inst->has_sharding()) { return partitions; } const auto& sharding = inst->sharding(); if (sharding.IsTileMaximal()) { return partitions; } for (const auto& dim : dims) { if (lhs_or_rhs == 0) { partitions *= sharding.tile_assignment().dim(dim.lhs); } else { CHECK_EQ(lhs_or_rhs, 1); partitions *= sharding.tile_assignment().dim(dim.rhs); } } return partitions; }; auto dot_dims = dot_as_convolution_util::ParseConvolutionDimsInfo(instruction); const int64_t lhs_conv_spatial_partitions = get_partitions_for_dims( instruction->operand(0), dot_dims.conv_spatial_dims, 0); const int64_t rhs_conv_spatial_partitions = get_partitions_for_dims( instruction->operand(1), dot_dims.conv_spatial_dims, 1); if (dot_dims.conv_spatial_dims.empty() || (lhs_conv_spatial_partitions == 1 && rhs_conv_spatial_partitions == 1 && instruction->batch_group_count() == 1 && instruction->feature_group_count() == 1)) { return InferDotShardingFromOperands(instruction, call_graph, dot_dims, may_combine_partial_sharding, is_spmd); } const auto& dnums = instruction->convolution_dimension_numbers(); const HloInstruction* lhs = instruction->operand(0); auto get_tiled_sharding_based_on_lhs = [&] { CHECK(!lhs->sharding().IsTileMaximal()); std::vector<int64_t> output_to_lhs_indices(instruction->shape().rank()); output_to_lhs_indices[dnums.output_batch_dimension()] = dnums.input_batch_dimension(); output_to_lhs_indices[dnums.output_feature_dimension()] = dnums.input_feature_dimension(); for (int64_t i = 0; i < dnums.input_spatial_dimensions_size(); ++i) { output_to_lhs_indices[dnums.output_spatial_dimensions(i)] = dnums.input_spatial_dimensions(i); } return hlo_sharding_util::TransposeSharding(lhs->sharding(), output_to_lhs_indices); }; if (!hlo_sharding_util::IsSpatiallyPartitioned(lhs)) { return false; } if (lhs->sharding().IsTileMaximal()) { return MaybeImproveInstructionSharding(lhs->sharding(), instruction, may_combine_partial_sharding); } if (IsConvolutionKernelSmall(instruction)) { // If the kernel is small compared to the input then we can generate an // output what is sharded the same way as the input. const auto& tile_assignment = lhs->sharding().tile_assignment(); if (tile_assignment.dim(dnums.input_feature_dimension()) > 1) { return false; } return MaybeImproveInstructionSharding(get_tiled_sharding_based_on_lhs(), instruction, may_combine_partial_sharding); } // If the kernel is large (e.g., backward convolution) then we only support // replicated output. We intend to keep the sharding along the batch dimension // between lhs and output. return MaybeImproveInstructionSharding( hlo_sharding_util::PartiallyReplicateTiledShardingOnAllDimsExcept( lhs->sharding(), {dnums.input_batch_dimension()}), instruction, may_combine_partial_sharding); } [&](const HloInstruction* inst, absl::Span< const dot_as_convolution_util::DotConvolutionDimsInfo::DimNums> dims, int lhs_or_rhs) { int64_t partitions = 1; if (!inst->has_sharding()) { return partitions; } const auto& sharding = inst->sharding(); if (sharding.IsTileMaximal()) { return partitions; } for (const auto& dim : dims) { if (lhs_or_rhs == 0) { partitions *= sharding.tile_assignment().dim(dim.lhs); } else { CHECK_EQ(lhs_or_rhs, 1); partitions *= sharding.tile_assignment().dim(dim.rhs); } } return partitions; }; auto get_tiled_sharding_based_on_lhs = [&] { CHECK(!lhs->sharding().IsTileMaximal()); std::vector<int64_t> output_to_lhs_indices(instruction->shape().rank()); output_to_lhs_indices[dnums.output_batch_dimension()] = dnums.input_batch_dimension(); output_to_lhs_indices[dnums.output_feature_dimension()] = dnums.input_feature_dimension(); for (int64_t i = 0; i < dnums.input_spatial_dimensions_size(); ++i) { output_to_lhs_indices[dnums.output_spatial_dimensions(i)] = dnums.input_spatial_dimensions(i); } return hlo_sharding_util::TransposeSharding(lhs->sharding(), output_to_lhs_indices); }; std::optional<HloSharding> InferBroadcastOperandSharding( const HloInstruction& instruction, bool is_spmd) { if (instruction.sharding().IsReplicated() || instruction.sharding().IsManual()) { return instruction.sharding(); } std::vector<int64_t> dims_to_replicate; bool needs_replication = false; for (int64_t i = 0; i < instruction.shape().rank(); ++i) { if (absl::c_count(instruction.dimensions(), i) == 0) { dims_to_replicate.push_back(i); if (instruction.sharding().tile_assignment().dim(i) > 1) { needs_replication = true; } } } // If not SPMD, only support when none of the partitioned dimensions in // the broadcast output belong to new dimensions. if (!is_spmd && needs_replication) { return std::nullopt; } return hlo_sharding_util::RemoveShapeDimensions( hlo_sharding_util::PartiallyReplicateTiledShardingOnDims( instruction.sharding(), dims_to_replicate), dims_to_replicate); } bool InferReduceShardingFromOperand(HloInstruction* instruction, bool may_combine_partial_sharding, bool is_spmd) { auto get_maybe_tuple_sharding = [&](HloSharding sharding) { if (instruction->shape().IsArray()) { return sharding; } std::vector<HloSharding> tuple(instruction->shape().tuple_shapes_size(), std::move(sharding)); return HloSharding::Tuple(instruction->shape(), tuple); }; auto* reduce = Cast<HloReduceInstruction>(instruction); bool changed = false; for (HloInstruction* operand : reduce->inputs()) { if (!hlo_sharding_util::IsSpatiallyPartitioned(operand)) { continue; } if (operand->sharding().IsReplicated() || (!is_spmd && absl::c_any_of(instruction->dimensions(), [operand](int64_t dim) { return operand->sharding().tile_assignment().dim(dim) > 1; }))) { // We are reducing along one of the sharded dimensions. We only // support this in SPMD. changed |= MaybeImproveInstructionSharding( get_maybe_tuple_sharding( hlo_sharding_util::ReplicateAllDataDims(operand->sharding())), reduce, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); continue; } auto after_partial_replication = operand->sharding().IsReplicated() ? operand->sharding() : hlo_sharding_util::PartiallyReplicateTiledShardingOnDims( operand->sharding(), reduce->dimensions()); if (after_partial_replication.IsReplicated()) { changed |= MaybeImproveInstructionSharding( get_maybe_tuple_sharding(after_partial_replication), reduce, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); continue; } // Use the same sharding for all tuple elements, because they are part // of the same reduce instruction. HloSharding new_sharding = get_maybe_tuple_sharding(hlo_sharding_util::RemoveShapeDimensions( after_partial_replication, reduce->dimensions())); changed |= MaybeImproveInstructionSharding( std::move(new_sharding), reduce, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(reduce) == 1); } return changed; } auto get_maybe_tuple_sharding = [&](HloSharding sharding) { if (instruction->shape().IsArray()) { return sharding; } std::vector<HloSharding> tuple(instruction->shape().tuple_shapes_size(), std::move(sharding)); return HloSharding::Tuple(instruction->shape(), tuple); }; absl::c_any_of(instruction->dimensions(), [operand](int64_t dim) { return operand->sharding().tile_assignment().dim(dim) > 1; }))) { absl::StatusOr<bool> ProcessShardingInstruction( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads, bool replace_sharding_with_copy, absl::flat_hash_map<const HloInstruction*, std::vector<int64_t>>* unspecified_dims, std::vector<HloSharding>* saved_root_shardings, absl::flat_hash_map<int64_t, HloSharding>* saved_parameter_shardings, absl::flat_hash_map<HloInstruction*, int64_t>* instruction_to_shard_group_id, absl::flat_hash_map<int64_t, absl::flat_hash_set<HloInstruction*>>* shard_group_id_to_shard_as_group, absl::flat_hash_map<int64_t, absl::flat_hash_set<HloInstruction*>>* shard_group_id_to_shard_like_group, const std::vector<bool>* allow_spmd_sharding_propagation_to_parameters_vector) { bool changed = false; const bool use_shard_group = instruction_to_shard_group_id && shard_group_id_to_shard_as_group && shard_group_id_to_shard_like_group; // Process shard group instruction and returns if current instruction needs // to be removed. auto process_shard_group_instruction = [&](HloInstruction* instruction, bool replaced_with_copy) -> absl::StatusOr<bool> { // Run shard group processing IFF it's not CSE prevention. if (replace_sharding_with_copy) { if (use_shard_group && instruction->has_sharding() && instruction->sharding().IsShardGroup()) { if (instruction->IsCustomCall("Sharding")) { CHECK(instruction->operand(0)->opcode() != HloOpcode::kParameter || (allow_spmd_sharding_propagation_to_parameters_vector && allow_spmd_sharding_propagation_to_parameters_vector->size() == module->entry_computation()->num_parameters() && allow_spmd_sharding_propagation_to_parameters_vector->at( instruction->operand(0)->parameter_number()))); } if (instruction->IsCustomCall("Sharding") && !replaced_with_copy) { // Pass shard group to operand sharding custom-call if it's not // replaced with a copy, meaning that the shardings are to annotate // shard_group. HloSharding operand_sharding = instruction->operand(0)->has_sharding() ? instruction->operand(0)->sharding() : HloSharding::Unknown(); operand_sharding.SetShardGroup( instruction->sharding().GetShardGroup()); instruction->mutable_operand(0)->set_sharding( std::move(operand_sharding)); return true; } else { // Otherwise store the shard group relations. const int64_t shard_group_id = instruction->sharding().GetShardGroup().shard_group_id; (*instruction_to_shard_group_id)[instruction] = shard_group_id; if (instruction->sharding().IsShardAs()) { auto& shard_as_group = (*shard_group_id_to_shard_as_group)[shard_group_id]; if (!shard_as_group.empty()) { CHECK(ShapeUtil::SameDimensions( instruction->shape(), (*shard_as_group.begin())->shape())) << "Instruction: " << instruction->ToString() << " has different shape from the shapes of the other " "instructions within the same shard_as group: " << (*shard_as_group.begin())->shape().ToString(); } shard_as_group.insert(instruction); } else { auto& shard_like_group = (*shard_group_id_to_shard_like_group)[shard_group_id]; if (!shard_like_group.empty()) { CHECK(ShapeUtil::SameDimensions( instruction->shape(), (*shard_like_group.begin())->shape())) << "Instruction: " << instruction->ToString() << " has different shape from the shapes of the other " "instructions within the same shard_like group: " << (*shard_like_group.begin())->shape().ToString(); } shard_like_group.insert(instruction); } HloSharding sharding = instruction->sharding(); sharding.ClearShardGroup(); instruction->set_sharding(std::move(sharding)); } } } return false; }; for (HloComputation* computation : module->computations(execution_threads)) { auto instructions = computation->MakeInstructionPostOrder(); for (auto it = instructions.rbegin(); it != instructions.rend(); ++it) { HloInstruction* instruction = *it; if (instruction->IsCustomCall("Sharding")) { HloSharding original_sharding = instruction->sharding(); TF_RET_CHECK(instruction->has_sharding()) << "Sharding instruction must have a sharding attribute"; VLOG(3) << "ProcessShardingInstruction: " << instruction->ToString(); std::vector<int64_t> unspec_dims; TF_RETURN_IF_ERROR(sharding_op_util::ParseAttributes( Cast<HloCustomCallInstruction>(instruction)->opaque(), &unspec_dims)); bool replaced_with_copy = replace_sharding_with_copy && (!original_sharding.IsUnknown() || instruction->operand(0)->opcode() == HloOpcode::kParameter); // Replace the sharding instruction with a copy node so that it does not // need special handling. if (replaced_with_copy) { auto copy = computation->AddInstruction(HloInstruction::CreateUnary( instruction->shape(), HloOpcode::kCopy, instruction->mutable_operand(0))); TF_ASSIGN_OR_RETURN( std::ignore, computation->ReplaceInstruction( instruction, copy, /*preserve_sharding=*/false, /*relay_control_dependency=*/false, /*remove_unused_operands=*/false)); copy->set_sharding(std::move(original_sharding)); instruction = copy; changed = true; } TF_ASSIGN_OR_RETURN( bool shard_group_remove_instruction, process_shard_group_instruction(instruction, replaced_with_copy)); if (!unspec_dims.empty()) { absl::c_sort(unspec_dims); unspecified_dims->emplace(instruction, std::move(unspec_dims)); } else if (!instruction->operand(0)->has_sharding()) { instruction->mutable_operand(0)->set_sharding( instruction->sharding()); } if (shard_group_remove_instruction) { TF_ASSIGN_OR_RETURN(std::ignore, computation->ReplaceInstruction( instruction, instruction->mutable_operand(0), /*preserve_sharding=*/false, /*relay_control_dependency=*/false, /*remove_unused_operands=*/false)); } } else { TF_ASSIGN_OR_RETURN(std::ignore, process_shard_group_instruction( instruction, /*replaced_with_copy=*/false)); } } } // Save the original shardings of parameters/outputs. HloInstruction* root_instr = module->entry_computation()->root_instruction(); if (saved_root_shardings != nullptr && root_instr->shape().IsTuple() && root_instr->has_sharding()) { saved_root_shardings->reserve( root_instr->sharding().tuple_elements().size()); for (const HloSharding& sharding : root_instr->sharding().tuple_elements()) { saved_root_shardings->push_back(sharding); } } if (saved_parameter_shardings != nullptr) { auto params = module->entry_computation()->parameter_instructions(); for (int64_t i = 0; i < params.size(); ++i) { if (params[i]->has_sharding()) { saved_parameter_shardings->insert({i, params[i]->sharding()}); } } } return changed; } [&](HloInstruction* instruction, bool replaced_with_copy) -> absl::StatusOr<bool> { // Run shard group processing IFF it's not CSE prevention. if (replace_sharding_with_copy) { if (use_shard_group && instruction->has_sharding() && instruction->sharding().IsShardGroup()) { if (instruction->IsCustomCall("Sharding")) { CHECK(instruction->operand(0)->opcode() != HloOpcode::kParameter || (allow_spmd_sharding_propagation_to_parameters_vector && allow_spmd_sharding_propagation_to_parameters_vector->size() == module->entry_computation()->num_parameters() && allow_spmd_sharding_propagation_to_parameters_vector->at( instruction->operand(0)->parameter_number()))); } if (instruction->IsCustomCall("Sharding") && !replaced_with_copy) { // Pass shard group to operand sharding custom-call if it's not // replaced with a copy, meaning that the shardings are to annotate // shard_group. HloSharding operand_sharding = instruction->operand(0)->has_sharding() ? instruction->operand(0)->sharding() : HloSharding::Unknown(); operand_sharding.SetShardGroup( instruction->sharding().GetShardGroup()); instruction->mutable_operand(0)->set_sharding( std::move(operand_sharding)); return true; } else { // Otherwise store the shard group relations. const int64_t shard_group_id = instruction->sharding().GetShardGroup().shard_group_id; (*instruction_to_shard_group_id)[instruction] = shard_group_id; if (instruction->sharding().IsShardAs()) { auto& shard_as_group = (*shard_group_id_to_shard_as_group)[shard_group_id]; if (!shard_as_group.empty()) { CHECK(ShapeUtil::SameDimensions( instruction->shape(), (*shard_as_group.begin())->shape())) << "Instruction: " << instruction->ToString() << " has different shape from the shapes of the other " "instructions within the same shard_as group: " << (*shard_as_group.begin())->shape().ToString(); } shard_as_group.insert(instruction); } else { auto& shard_like_group = (*shard_group_id_to_shard_like_group)[shard_group_id]; if (!shard_like_group.empty()) { CHECK(ShapeUtil::SameDimensions( instruction->shape(), (*shard_like_group.begin())->shape())) << "Instruction: " << instruction->ToString() << " has different shape from the shapes of the other " "instructions within the same shard_like group: " << (*shard_like_group.begin())->shape().ToString(); } shard_like_group.insert(instruction); } HloSharding sharding = instruction->sharding(); sharding.ClearShardGroup(); instruction->set_sharding(std::move(sharding)); } } } return false; }; VLOG(3) << "ProcessShardingInstruction: " << instruction->ToString(); int64_t ComputeNonRootUsers(const HloInstruction* instr) { int64_t non_root_users = instr->users().size(); for (int i = 0; i < instr->users().size(); ++i) { if (instr->users()[i] == instr->parent()->root_instruction()) { --non_root_users; } } return non_root_users; } /*static*/ absl::Status ShardingPropagation::NormalizeDomain( const DomainMetadata::Domain& domain, const DomainMetadata* metadata) { if (metadata != nullptr) { TF_ASSIGN_OR_RETURN(const auto& sharding_metadata, ShardingMetadata::ToShardingMetadata(metadata)); const auto& sharding = sharding_metadata->sharding(); if (sharding != nullptr) { bool is_spatially_partitioned = !sharding->HasUniqueDevice(); if (sharding->IsTuple()) { is_spatially_partitioned = absl::c_any_of( sharding->tuple_elements(), [](const HloSharding& s) { return !s.HasUniqueDevice(); }); } if (is_spatially_partitioned) { for (HloInstruction* d : domain.exit_domains) { HloInstruction* operand = d->mutable_operand(0); // Set sharding only if it is different. We don't overwrite the // metadata if it has the same sharding besides metadata. if (!operand->has_sharding() || operand->sharding() != *sharding) { HloSharding operand_sharding = *sharding; if (operand->shape().IsTuple() && !sharding->IsTuple()) { // Expand sharding into tuple sharding per // CloneShardingForDomain() in // third_party/tensorflow/compiler/xla/hlo/ir/hlo_sharding_metadata.cc operand_sharding = HloSharding::SingleTuple(operand->shape(), *sharding); } operand->set_sharding(std::move(operand_sharding)); } } return absl::OkStatus(); } } } return ShardingMetadata::NormalizeShardingDomain(domain, metadata); } std::optional<HloSharding> ShardingPropagation::GetShardingFromUser( const HloInstruction& instruction, const HloInstruction& user, int64_t aggressiveness, bool is_spmd, const CallGraph& call_graph, const CustomCallShardingHelper* sharding_helper) { if (!CanPropagateThroughAtAggressiveLevel(user, aggressiveness)) { return std::nullopt; } if (!hlo_sharding_util::IsSpatiallyPartitioned(&user)) { return std::nullopt; } const bool may_combine_partial_sharding = is_spmd && aggressiveness > 0; switch (user.opcode()) { case HloOpcode::kBroadcast: { return InferBroadcastOperandSharding(user, is_spmd); } case HloOpcode::kConcatenate: { if (aggressiveness == 0) { return std::nullopt; } if (user.sharding().IsReplicated()) { return user.sharding(); } const int64_t cdim = user.concatenate_dimension(); auto& tile_assignment = user.sharding().tile_assignment(); if (tile_assignment.dim(cdim) == 1) { // If we are concatenating along a non-sharded dimension then the // operands should have the same sharding as the result. return user.sharding(); } if (is_spmd) { // SPMD doesn't support tiling with part of the devices. Return the same // sharding. return user.sharding(); } // If we are concatenating along a sharded dimension then we want the // operands to be distributed among the devices their data is used. int64_t start_offset = 0; for (HloInstruction* op : user.operands()) { if (op == &instruction) { break; } start_offset += op->shape().dimensions(cdim); } const int64_t tile_shape = CeilOfRatio( user.shape().dimensions(cdim), tile_assignment.dimensions()[cdim]); std::vector<int64_t> start_indices(tile_assignment.num_dimensions()); std::vector<int64_t> end_indices(tile_assignment.dimensions().begin(), tile_assignment.dimensions().end()); start_indices[cdim] = start_offset / tile_shape; end_indices[cdim] = CeilOfRatio( start_offset + instruction.shape().dimensions(cdim), tile_shape); auto new_tile_assignment = tile_assignment.array().Slice(start_indices, end_indices); if (new_tile_assignment.num_elements() == 1) { return HloSharding::AssignDevice(*new_tile_assignment.begin(), user.sharding().metadata()); } return HloSharding::Tile(std::move(new_tile_assignment), user.sharding().metadata()); } case HloOpcode::kConvolution: { auto dot_dims = dot_as_convolution_util::ParseConvolutionDimsInfo(&user); if (dot_dims.conv_spatial_dims.empty()) { int64_t op_idx = user.operand_index(&instruction); return hlo_sharding_util::InferDotOperandSharding( &user, op_idx, dot_dims, /*consider_other_operand=*/true, may_combine_partial_sharding); } return std::nullopt; } case HloOpcode::kDynamicSlice: case HloOpcode::kDynamicUpdateSlice: { if (aggressiveness == 0) { return std::nullopt; } if (user.sharding().IsReplicated()) { return user.sharding(); } if (user.opcode() == HloOpcode::kDynamicUpdateSlice && &instruction == user.operand(0)) { return user.sharding(); } const HloInstruction* operand = user.opcode() == HloOpcode::kDynamicSlice ? user.operand(0) : user.operand(1); if (&instruction != operand) { return std::nullopt; } if (is_spmd) { return user.sharding(); } const auto& tile_assignment = user.sharding().tile_assignment(); for (int64_t i = 0; i < user.shape().rank(); ++i) { if (tile_assignment.dim(i) > 1 && user.shape().dimensions(i) != operand->shape().dimensions(i)) { return std::nullopt; } } return user.sharding(); } case HloOpcode::kReduceWindow: { auto* reduce_window = Cast<HloReduceWindowInstruction>(&user); if (!absl::c_linear_search(reduce_window->inputs(), &instruction)) { return std::nullopt; } if (reduce_window->shape().IsTuple()) { auto sub_sharding = reduce_window->sharding().GetSubSharding( reduce_window->shape(), {reduce_window->operand_index(&instruction)}); return sub_sharding; } return reduce_window->sharding(); } case HloOpcode::kReshape: { return hlo_sharding_util::PropagateShardingThroughReshape( user.shape(), instruction.shape(), user.sharding()); } case HloOpcode::kPad: { if (&instruction != user.operand(0)) { return std::nullopt; } return user.sharding(); } case HloOpcode::kSlice: { return user.sharding(); } case HloOpcode::kTranspose: { // Calculate the dimension numbers for reversing the current transpose // and then use TransposeSharding to convert the output sharding to an // input sharding. std::vector<int64_t> reverse_dimensions(user.dimensions().size()); for (int64_t i = 0; i < user.dimensions().size(); ++i) { reverse_dimensions[user.dimensions(i)] = i; } return hlo_sharding_util::TransposeSharding(user.sharding(), reverse_dimensions); } case HloOpcode::kTuple: { auto sub_sharding = user.sharding().GetSubSharding( user.shape(), {user.operand_index(&instruction)}); // In case the instruction is used as the operands multiple times within // this tuple, we will return the most specific sharding and propagate up. for (int64_t i = 0; i < user.shape().tuple_shapes_size(); ++i) { if (user.operand(i) == &instruction) { // Only evaluate GetSubSharding if this operand is of interest, // as it is relatively expensive. HloSharding alternative_sub_sharding = user.sharding().GetSubSharding(user.shape(), {i}); if (hlo_sharding_util::IsShardingMoreSpecific( alternative_sub_sharding, sub_sharding)) { sub_sharding = alternative_sub_sharding; } } } return sub_sharding; } case HloOpcode::kGetTupleElement: { int64_t sharding_index = 0; for (int i = 0; i < instruction.shape().tuple_shapes_size(); ++i) { if (i == user.tuple_index()) { break; } if (instruction.shape().tuple_shapes(i).IsArray()) { sharding_index += 1; } else { sharding_index += ShapeUtil::GetLeafCount(instruction.shape().tuple_shapes(i)); } } if (user.shape().IsArray()) { // Use ReplicateAllDataDims instead of HloSharding::Replicate() to // preserve manual subgroups. HloSharding new_sharding = instruction.has_sharding() ? instruction.sharding() : HloSharding::SingleTuple( instruction.shape(), hlo_sharding_util::ReplicateAllDataDims(user.sharding())); new_sharding.tuple_elements()[sharding_index] = user.sharding(); return new_sharding; } else { if (user.sharding().tuple_elements().empty()) { return std::nullopt; } HloSharding new_sharding = instruction.has_sharding() ? instruction.sharding() : HloSharding::SingleTuple( instruction.shape(), hlo_sharding_util::ReplicateAllDataDims( user.sharding().tuple_elements()[0])); for (int64_t i = 0; i < user.sharding().tuple_elements().size(); ++i) { new_sharding.tuple_elements()[sharding_index + i] = user.sharding().tuple_elements()[i]; } return new_sharding; } } case HloOpcode::kDot: { int64_t op_idx = user.operand_index(&instruction); auto dnums = dot_as_convolution_util::ParseDotGeneralFromDot(&user); return hlo_sharding_util::InferDotOperandSharding( &user, op_idx, dnums, /*consider_other_operand=*/true, may_combine_partial_sharding); } case HloOpcode::kReduce: { if (instruction.shape().rank() == 0) { return std::nullopt; } auto user_sharding = user.shape().IsTuple() ? user.sharding().GetSubSharding( user.shape(), {user.operand_index(&instruction)}) : user.sharding(); if (!user_sharding.IsTileMaximal()) { std::vector<int64_t> target_tile_assignment_dimensions( instruction.shape().rank() + (user_sharding.ReplicateOnLastTileDim() ? 1 : 0) + user_sharding.subgroup_types().size()); const auto& dimensions = user.dimensions(); int64_t next_output_dim = 0; for (int64_t i = 0; i < target_tile_assignment_dimensions.size(); ++i) { if (absl::c_find(dimensions, i) == dimensions.end()) { target_tile_assignment_dimensions[i] = user_sharding.tile_assignment().dim(next_output_dim++); } else { target_tile_assignment_dimensions[i] = 1; } } auto tile_assignment = user_sharding.tile_assignment().Reshape( target_tile_assignment_dimensions); user_sharding = user_sharding.ReplicateOnLastTileDim() ? HloSharding::PartialTile(tile_assignment, user_sharding.metadata()) : HloSharding::Subgroup(tile_assignment, user_sharding.subgroup_types(), user_sharding.metadata()); } // Try to merge with sharding from other operands if they can improve // current sharding. const auto* reduce = Cast<const HloReduceInstruction>(&user); for (const HloInstruction* operand : reduce->inputs()) { if (operand != &instruction && operand->has_sharding()) { hlo_sharding_util::MergeShardingIfCompatible( operand->sharding(), user_sharding.NumTiles() + 1, &user_sharding); } } return user_sharding; } case HloOpcode::kSort: { HloSharding user_sharding = user.sharding(); if (user_sharding.IsTuple()) { return user_sharding.GetSubSharding(user.shape(), {user.operand_index(&instruction)}); } return user_sharding; } case HloOpcode::kReverse: { return hlo_sharding_util::ReverseSharding(user.sharding(), user.dimensions()); } case HloOpcode::kOutfeed: { if (&instruction != user.operand(0)) { return std::nullopt; } std::vector<Shape> operand_shapes(user.operand_count()); for (int i = 0; i < user.operand_count(); ++i) { operand_shapes[i] = user.operand(i)->shape(); } return user.sharding().GetSubSharding( ShapeUtil::MakeTupleShape(operand_shapes), {0}); } case HloOpcode::kGather: { if (&instruction == user.operand(1)) { return hlo_sharding_util:: GatherIndexShardingFromOutputIndexPassthroughDimensions( user.sharding(), &user); } if (is_spmd) { return hlo_sharding_util::GatherOperandShardingFromOutput( user.sharding(), user, call_graph); } return std::nullopt; } case HloOpcode::kScatter: { auto& scatter_user = *Cast<HloScatterInstruction>(&user); const int64_t operand_count = scatter_user.scatter_operand_count(); auto scatter_operands = scatter_user.scatter_operands(); auto scatter_indices = scatter_user.scatter_indices(); auto scatter_updates = scatter_user.scatter_updates(); // Infer sharding for scatter operand. const int64_t operand_index = absl::c_find(scatter_operands, &instruction) - scatter_operands.cbegin(); if (operand_index < operand_count) { return user.sharding().IsTuple() ? user.sharding().GetSubSharding( user.shape(), {operand_index}) : user.sharding(); } // Infer sharding for scatter indices. if (&instruction == scatter_indices) { std::vector<const HloInstruction*> partitioned_updates; for (const HloInstruction* update : scatter_updates) { if (hlo_sharding_util::IsSpatiallyPartitioned(update)) { partitioned_updates.push_back(update); } } if (partitioned_updates.empty()) { return std::nullopt; } std::vector<HloSharding> shardings; absl::c_transform( partitioned_updates, std::back_inserter(shardings), [&scatter_user](const HloInstruction* update) { return hlo_sharding_util:: ScatterIndexShardingFromUpdateIndexPassthroughDimensions( update->sharding(), &scatter_user); }); return hlo_sharding_util::FindCommonSharding(shardings); } // Infer sharding for scatter update. const int64_t update_index = absl::c_find(scatter_updates, &instruction) - scatter_updates.cbegin(); CHECK_LE(update_index, operand_count); auto from_indices = hlo_sharding_util::IsSpatiallyPartitioned(scatter_indices) ? hlo_sharding_util:: ScatterUpdateShardingFromIndexIndexPassthroughDimensions( scatter_indices->sharding(), &scatter_user) : HloSharding::Replicate(); if (is_spmd) { auto from_output = hlo_sharding_util::ScatterUpdateShardingFromOutput( user.sharding().IsTuple() ? user.sharding().GetSubSharding(user.shape(), {update_index}) : user.sharding(), scatter_user, call_graph); if (from_output.has_value()) { // Use sharding from output as primary sharding since it prioritize // parallel sharding first as this is how it is in spmd_partitioner. hlo_sharding_util::MergeShardingIfCompatible( from_indices, from_output->NumTiles() + 1, &*from_output); if (!from_output->IsTileMaximal()) { return from_output; } } } if (!from_indices.IsTileMaximal()) { return from_indices; } return std::nullopt; } case HloOpcode::kCustomCall: { bool compatible_shapes = ShapeUtil::CompatibleIgnoringElementType( instruction.shape(), user.shape()); if (!compatible_shapes) { // Incompatible shapes, we will not propagate sharding. return std::nullopt; } if (!sharding_helper) { // No available sharding helper and shapes are compatible, we will // propagate sharding. return user.sharding(); } if (sharding_helper->CanPropagateShardingToOperands(&user)) { return user.sharding(); } return std::nullopt; } default: { // If the user output shape is compatible with the current instruction // shape excluding element type and the current instruction is supported // by spatial partitioning, then the user sharding can be used for // propagation to the current instruction. if (ShapeUtil::CompatibleIgnoringElementType(instruction.shape(), user.shape())) { return user.sharding(); } return std::nullopt; } } } [&scatter_user](const HloInstruction* update) { return hlo_sharding_util:: ScatterIndexShardingFromUpdateIndexPassthroughDimensions( update->sharding(), &scatter_user); }); bool AggressiveConcatOperandShardingCanPassThrough( const HloInstruction* concat_operand) { return ( hlo_sharding_util::IsSpatiallyPartitioned(concat_operand) && (concat_operand->has_sharding() && concat_operand->sharding().NumTiles() > 1) && concat_operand->opcode() == HloOpcode::kReshape && (concat_operand->operand(0)->opcode() == HloOpcode::kParameter || concat_operand->operand(0)->opcode() == HloOpcode::kGetTupleElement)); } bool InferDynamicSliceOrDynamicUpdateSliceShardingFromOperands( HloInstruction* instruction, int64_t aggressiveness, bool may_combine_partial_sharding) { const HloInstruction* operand = instruction->opcode() == HloOpcode::kDynamicSlice ? instruction->operand(0) : instruction->operand(1); auto slice_dim_is_sharded = [&]() { if (!hlo_sharding_util::IsSpatiallyPartitioned(operand) || operand->sharding().IsManual() || operand->sharding().NumTiles() == 1) { return false; } for (int64_t i = 0; i < instruction->shape().rank(); ++i) { const auto& tile_assignment = operand->sharding().tile_assignment(); if (tile_assignment.dim(i) > 1 && instruction->shape().dimensions(i) != operand->shape().dimensions(i)) { return true; } } return false; }; // Do not pass through sharding annotation at the first iteration // if slice dim is sharded. if (aggressiveness == 0 && slice_dim_is_sharded()) { return false; } auto propagate_slicing = [&]() { if (!hlo_sharding_util::IsSpatiallyPartitioned(operand)) { return false; } if (slice_dim_is_sharded()) { return false; } return MaybeImproveInstructionSharding( operand->sharding(), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); }; auto propagate_base = [&]() { if (instruction->opcode() != HloOpcode::kDynamicUpdateSlice) { return false; } if (!hlo_sharding_util::IsSpatiallyPartitioned(instruction->operand(0))) { return false; } return MaybeImproveInstructionSharding(instruction->operand(0)->sharding(), instruction, may_combine_partial_sharding); }; bool changed = propagate_slicing(); changed |= propagate_base(); return changed; } auto slice_dim_is_sharded = [&]() { if (!hlo_sharding_util::IsSpatiallyPartitioned(operand) || operand->sharding().IsManual() || operand->sharding().NumTiles() == 1) { return false; } for (int64_t i = 0; i < instruction->shape().rank(); ++i) { const auto& tile_assignment = operand->sharding().tile_assignment(); if (tile_assignment.dim(i) > 1 && instruction->shape().dimensions(i) != operand->shape().dimensions(i)) { return true; } } return false; }; auto propagate_slicing = [&]() { if (!hlo_sharding_util::IsSpatiallyPartitioned(operand)) { return false; } if (slice_dim_is_sharded()) { return false; } return MaybeImproveInstructionSharding( operand->sharding(), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); }; auto propagate_base = [&]() { if (instruction->opcode() != HloOpcode::kDynamicUpdateSlice) { return false; } if (!hlo_sharding_util::IsSpatiallyPartitioned(instruction->operand(0))) { return false; } return MaybeImproveInstructionSharding(instruction->operand(0)->sharding(), instruction, may_combine_partial_sharding); }; bool ShardingPropagation::InferShardingFromShardGroup( HloInstruction* instruction, const ComputationMap& computation_map, int64_t aggressiveness, const absl::flat_hash_set<HloInstruction*>& shard_group) { if (!CanPropagateThroughAtAggressiveLevel(*instruction, aggressiveness)) { return false; } // Do not change manual sharding. if (instruction->has_sharding() && instruction->sharding().IsManual()) { return false; } // Do not propagate sharding to ShardBarrierTo custom-call. if (instruction->IsCustomCall(spmd::kShardBarrierTo)) { return false; } // Propagate manual sharding. if (!instruction->has_sharding() || instruction->sharding().IsTileMaximal()) { for (const HloInstruction* member : shard_group) { if (!member->has_sharding() || !member->sharding().IsManual() || member == instruction) { continue; } instruction->set_sharding(member->sharding()); return true; } } const bool may_combine_partial_sharding = is_spmd_ && aggressiveness > 0; bool changed = false; for (const HloInstruction* member : shard_group) { // Do not propagate sharding from ShardBarrierFrom custom-call. if (member == instruction || member->IsCustomCall(spmd::kShardBarrierFrom)) { continue; } changed |= MaybeImproveInstructionSharding(member->sharding(), instruction, may_combine_partial_sharding); } return changed; } bool ShardingPropagation::InferShardingFromOperands( HloInstruction* instruction, const ComputationMap& computation_map, int64_t aggressiveness, const CallGraph& call_graph, const absl::flat_hash_set<absl::string_view>& execution_threads) { if (!CanPropagateThroughAtAggressiveLevel(*instruction, aggressiveness)) { return false; } // Do not change manual sharding. if (instruction->has_sharding() && instruction->sharding().IsManual()) { return false; } // Propagate manual sharding. Avoid tuple shaped HLOs that group independent // together. Reduce, ReduceWindow, and Sort can be tuples but the elements // are correlated, so we propagate manual sharding through them. // For custom-calls with manual operand, the default propagation logic will // just assign manual to the whole custom-call. const bool custom_call_condition = instruction->opcode() == HloOpcode::kCustomCall && instruction->shape().IsTuple(); // For asynchronous instructions with manual operand, we assign manual to the // whole instructions if the async_execution_thread is not in the // execution_threads. const bool async_instr_condition = instruction->IsAsynchronous() && !HloInstruction::IsThreadIncluded(instruction->async_execution_thread(), execution_threads); if ((!instruction->has_sharding() || instruction->sharding().IsTileMaximal()) && (instruction->shape().IsArray() || instruction->opcode() == HloOpcode::kReduce || instruction->opcode() == HloOpcode::kSort || instruction->opcode() == HloOpcode::kReduceWindow || custom_call_condition || async_instr_condition)) { for (const HloInstruction* op : instruction->operands()) { if (!op->has_sharding() || !op->sharding().IsManual()) continue; // Do not pass through manual sharding to SPMDShardToFullShape. if (instruction->IsCustomCall("SPMDShardToFullShape")) { return false; } // Do not pass through manual sharding to concat or dynamic slice when // aggressiveneess is 0. if (aggressiveness == 0 && (instruction->opcode() == HloOpcode::kConcatenate || instruction->opcode() == HloOpcode::kDynamicSlice)) { return false; } instruction->set_sharding( HloSharding::Manual(op->sharding().metadata()) .NormalizeTupleSharding(instruction->shape())); return true; } } const bool may_combine_partial_sharding = is_spmd_ && aggressiveness > 0; if (!SupportSpatialPartitioning( instruction, computation_map, is_spmd_, allow_spmd_sharding_propagation_to_output_, /*allow_spmd_sharding_propagation_to_parameters=*/false, sharding_helper_.get())) { // If an array shaped HLO doesn't support spatial partitioning but at least // one of its operand is replicated then we make the HLO replicated as well. if (instruction->shape().IsTuple() || instruction->operand_count() == 0 || instruction == instruction->parent()->root_instruction() || instruction->HasSideEffect()) { return false; } for (const HloInstruction* op : instruction->operands()) { if (op->has_sharding() && op->sharding().IsTileMaximal() && !op->sharding().HasUniqueDevice()) { return MaybeImproveInstructionSharding(op->sharding(), instruction, may_combine_partial_sharding); } } return false; } auto get_maybe_tuple_sharding = [&](HloSharding sharding) { if (instruction->shape().IsArray()) { return sharding; } std::vector<HloSharding> tuple(instruction->shape().tuple_shapes_size(), std::move(sharding)); return HloSharding::Tuple(instruction->shape(), tuple); }; switch (instruction->opcode()) { case HloOpcode::kGetTupleElement: { const HloInstruction* operand = instruction->operand(0); if (!hlo_sharding_util::IsSpatiallyPartitioned(operand)) { return false; } HloSharding new_sharding = operand->sharding().GetSubSharding( operand->shape(), {instruction->tuple_index()}); if (new_sharding.IsManual()) { instruction->set_sharding(std::move(new_sharding)); return true; } return MaybeImproveInstructionSharding( std::move(new_sharding), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); } case HloOpcode::kTuple: { if (absl::c_none_of( instruction->operands(), [](const HloInstruction* hlo) { return hlo_sharding_util::IsSpatiallyPartitioned(hlo); })) { // None of the operands have a spatially partitioned sharding. return false; } const Shape& shape = instruction->shape(); // Go through each operand and if the operand has a sharding that is // better than the current sharding for that tuple element then update // it. If the current sharding does not exist, assume its replicated. std::vector<HloSharding> sub_shardings; if (instruction->has_sharding()) { sub_shardings = instruction->sharding().tuple_elements(); } else { // If instruction does not have a sharding, assume its replicated to // allow refinement. sub_shardings.assign(HloSharding::RequiredLeaves(shape), HloSharding::Replicate()); } // This is required to allow manual sharding on operands to be propagated // to the tuple. hlo_sharding_util::IsShardingMoreSpecific() returns false // if any of the shardings involved is manual, so using it directly will // prevent manual sharding on an operand to be propagated to the tuple // when it has no existing sharding. auto is_more_specific = [instruction](const HloSharding& operand_sharding, const HloSharding& existing) { // If the instruction originally had no sharding, always prefer operand // sharding. return !instruction->has_sharding() || hlo_sharding_util::IsShardingMoreSpecific(operand_sharding, existing); }; int64_t sub_sharding_index = 0; for (int64_t i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const HloInstruction* operand = instruction->operand(i); if (operand->has_sharding()) { if (operand->shape().IsTuple()) { for (int64_t j = 0, e = ShapeUtil::GetLeafCount(operand->shape()); j < e; ++j) { if (is_more_specific(operand->sharding().tuple_elements()[j], sub_shardings[sub_sharding_index + j])) { sub_shardings[sub_sharding_index + j] = operand->sharding().tuple_elements()[j]; } } } else { std::optional<HloSharding> op_sharding = hlo_sharding_util::GetOutputSharding(operand); CHECK(op_sharding.has_value()) << "Expected sharding for " << operand->ToString(); if (is_more_specific(op_sharding.value(), sub_shardings[sub_sharding_index])) { sub_shardings[sub_sharding_index] = op_sharding.value(); } } } sub_sharding_index += ShapeUtil::GetLeafCount(operand->shape()); } HloSharding new_sharding = HloSharding::Tuple(shape, sub_shardings); if (!instruction->has_sharding() || new_sharding != instruction->sharding()) { instruction->set_sharding(std::move(new_sharding)); return true; } return false; } case HloOpcode::kReduce: { // Reduce could have a tuple shape, where the first half of operands are // the arrays to reduce, and the second half of operands are the init // values. return InferReduceShardingFromOperand( instruction, may_combine_partial_sharding, is_spmd_); } case HloOpcode::kBroadcast: { // Make forward propagation through broadcast low priority to avoid // resharding after broadcast. if (aggressiveness < 3) { return false; } const HloInstruction* op = instruction->operand(0); if (!hlo_sharding_util::IsSpatiallyPartitioned(op) || op->sharding().IsReplicated()) { return false; } // The output will be tiled along the broadcasted dimension the same way // as the input for the broadcast while the other dimensions are kept // non-tiled. std::vector<int64_t> target_tile_assignment_dimensions; const auto& dimensions = instruction->dimensions(); for (int64_t i = 0; i < instruction->shape().rank(); ++i) { auto it = absl::c_find(dimensions, i); if (it == dimensions.end()) { target_tile_assignment_dimensions.push_back(1); } else { const int64_t source_dim = std::distance(dimensions.begin(), it); target_tile_assignment_dimensions.push_back( op->sharding().tile_assignment().dim(source_dim)); } } for (int64_t i = op->sharding().TiledDataRank(); i < op->sharding().tile_assignment().num_dimensions(); ++i) { target_tile_assignment_dimensions.push_back( op->sharding().tile_assignment().dim(i)); } auto new_tile_assignment = op->sharding().tile_assignment().Reshape( target_tile_assignment_dimensions); HloSharding new_sharding = op->sharding().ReplicateOnLastTileDim() ? HloSharding::PartialTile(new_tile_assignment, op->sharding().metadata()) : HloSharding::Subgroup(new_tile_assignment, op->sharding().subgroup_types(), op->sharding().metadata()); return MaybeImproveInstructionSharding( std::move(new_sharding), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ComputeNonRootUsers(instruction) == 1); } case HloOpcode::kConcatenate: { const HloInstruction* operand = PickRepresentativeOperand(instruction); if (!operand || !hlo_sharding_util::IsSpatiallyPartitioned(operand)) { return false; } if (aggressiveness == 0) { for (const HloInstruction* concat_operand : instruction->operands()) { if (!AggressiveConcatOperandShardingCanPassThrough(concat_operand)) { return false; } const auto& tile_assignment = concat_operand->sharding().tile_assignment(); for (int64_t i = 0; i < instruction->shape().rank(); ++i) { if (absl::c_linear_search(instruction->dimensions(), i) && tile_assignment.dim(i) > 1) { return false; } } } } return MaybeImproveInstructionSharding( operand->sharding(), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ComputeNonRootUsers(instruction) == 1); } case HloOpcode::kConvolution: return InferConvolutionShardingFromOperands( instruction, call_graph, aggressiveness, may_combine_partial_sharding, is_spmd_); case HloOpcode::kTranspose: { const HloInstruction* input = instruction->operand(0); if (!hlo_sharding_util::IsSpatiallyPartitioned(input)) { return false; } HloSharding sharding = hlo_sharding_util::TransposeSharding( input->sharding(), instruction->dimensions()); return MaybeImproveInstructionSharding( std::move(sharding), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ComputeNonRootUsers(instruction) == 1); } case HloOpcode::kReduceWindow: { auto* reduce_window = Cast<HloReduceWindowInstruction>(instruction); auto has_dilation = [](const WindowDimension& dimensions) { return dimensions.base_dilation() > 1 || dimensions.window_dilation() > 1; }; if (absl::c_any_of(instruction->window().dimensions(), has_dilation)) { VLOG(2) << "Not applying sharding to reduce window because dilatation " "isn't supported yet: " << reduce_window->ToString(); return false; } bool changed = false; for (HloInstruction* operand : reduce_window->inputs()) { if (!hlo_sharding_util::IsSpatiallyPartitioned(operand)) { continue; } changed |= MaybeImproveInstructionSharding( get_maybe_tuple_sharding(operand->sharding()), reduce_window, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); } return changed; } case HloOpcode::kSelectAndScatter: { // Shard according to first operand, as output keeps the same shape. const HloInstruction* lhs = instruction->operand(0); if (!hlo_sharding_util::IsSpatiallyPartitioned(lhs)) { return false; } auto has_base_dilation = [](const WindowDimension& dimensions) { return dimensions.base_dilation() > 1; }; if (absl::c_any_of(instruction->window().dimensions(), has_base_dilation)) { VLOG(2) << "Not applying sharding to select-and-scatter because " "base dilation isn't supported yet: " << instruction->ToString(); return false; } return MaybeImproveInstructionSharding( lhs->sharding(), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ComputeNonRootUsers(instruction) == 1); } case HloOpcode::kReshape: { if (!hlo_sharding_util::IsSpatiallyPartitioned(instruction->operand(0))) { return false; } HloSharding new_sharding = hlo_sharding_util::PropagateShardingThroughReshape( instruction->operand(0)->shape(), instruction->shape(), instruction->operand(0)->sharding()); return MaybeImproveInstructionSharding( std::move(new_sharding), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); return false; } case HloOpcode::kReverse: { const HloInstruction* operand = instruction->operand(0); if (!hlo_sharding_util::IsSpatiallyPartitioned(operand)) { return false; } return MaybeImproveInstructionSharding( hlo_sharding_util::ReverseSharding(operand->sharding(), instruction->dimensions()), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ComputeNonRootUsers(instruction) == 1); } case HloOpcode::kDot: { const auto& dnums = dot_as_convolution_util::ParseDotGeneralFromDot(instruction); return InferDotShardingFromOperands(instruction, call_graph, dnums, may_combine_partial_sharding, is_spmd_); } case HloOpcode::kParameter: { auto parent_it = computation_map.find(instruction->parent()); if (parent_it == computation_map.end()) { return false; } const HloInstruction* parent = parent_it->second; switch (parent->opcode()) { case HloOpcode::kConditional: { for (int64_t i = 1; i < parent->operand_count(); ++i) { if (parent->called_computations()[i - 1] == instruction->parent()) { if (parent->operand(i)->has_sharding()) { return MaybeImproveInstructionSharding( parent->operand(i)->sharding(), instruction, may_combine_partial_sharding); } return false; } } return false; } case HloOpcode::kCall: { int64_t i = instruction->parameter_number(); if (parent->operand(i)->has_sharding()) { return MaybeImproveInstructionSharding( parent->operand(i)->sharding(), instruction, may_combine_partial_sharding); } return false; } default: return false; } } case HloOpcode::kSort: { const HloInstruction* operand = PickRepresentativeOperand(instruction); if (!operand || !hlo_sharding_util::IsSpatiallyPartitioned(operand)) { return false; } HloSortInstruction* sort = DynCast<HloSortInstruction>(instruction); CHECK(sort); const int64_t sort_dim = sort->sort_dimension(); if (!operand->sharding().IsTileMaximal() && operand->sharding().tile_assignment().dim(sort_dim) != 1) { // In case of a sort operand sharded along the sort dimension, the // sharding is propagated only if there exists a free (unsharded) // dimension that we can later move the sharding into. if (!hlo_sharding_util::IsSortOperandShardingMovable(operand, sort_dim)) return false; } if (instruction->shape().IsTuple()) { return MaybeImproveInstructionSharding( HloSharding::SingleTuple(instruction->shape(), operand->sharding()), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); } else { return MaybeImproveInstructionSharding( operand->sharding(), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); } } case HloOpcode::kDynamicSlice: case HloOpcode::kDynamicUpdateSlice: { return InferDynamicSliceOrDynamicUpdateSliceShardingFromOperands( instruction, aggressiveness, may_combine_partial_sharding); } case HloOpcode::kGather: { bool changed = false; if (hlo_sharding_util::IsSpatiallyPartitioned(instruction->operand(1))) { HloSharding new_sharding = hlo_sharding_util:: GatherOutputShardingFromIndexIndexPassthroughDimensions( instruction->operand(1)->sharding(), instruction); changed |= MaybeImproveInstructionSharding( std::move(new_sharding), instruction, may_combine_partial_sharding); } if (is_spmd_) { auto gather_parallel_dims = hlo_sharding_util::GetGatherParallelBatchDims(*instruction, call_graph); if (gather_parallel_dims) { changed |= InferGatherParallelShardingFromOperands( instruction, *gather_parallel_dims, may_combine_partial_sharding); } if (hlo_sharding_util::IsSpatiallyPartitioned( instruction->operand(0))) { absl::Span<const int64_t> operand_parallel_dims; if (gather_parallel_dims) { operand_parallel_dims = absl::MakeConstSpan( gather_parallel_dims->operand_parallel_dims); } HloSharding filtered_operand_sharding = hlo_sharding_util::PartiallyReplicateTiledShardingOnDims( instruction->operand(0)->sharding(), operand_parallel_dims); auto maybe_from_data = hlo_sharding_util:: GatherOutputShardingFromOperandOperandPassthroughDimensions( filtered_operand_sharding, *instruction); if (maybe_from_data) { changed |= MaybeImproveInstructionSharding( std::move(*maybe_from_data), instruction, may_combine_partial_sharding); } } } return changed; } case HloOpcode::kScatter: { auto& scatter = *Cast<HloScatterInstruction>(instruction); const int64_t operand_count = scatter.scatter_operand_count(); auto scatter_operands = scatter.scatter_operands(); auto scatter_indices = scatter.scatter_indices(); auto scatter_updates = scatter.scatter_updates(); bool changed = false; if (is_spmd_) { for (int64_t i = 0; i != operand_count; ++i) { if (hlo_sharding_util::IsSpatiallyPartitioned(scatter_operands[i])) { changed |= MaybeImproveInstructionSubSharding( scatter_operands[i]->sharding(), instruction, {i}, may_combine_partial_sharding); } } if (!hlo_sharding_util::IsSpatiallyPartitioned(scatter_indices) && absl::c_none_of(scatter_updates, [](const HloInstruction* update) { return hlo_sharding_util::IsSpatiallyPartitioned(update); })) { return changed; } auto scatter_parallel_dims = hlo_sharding_util::GetScatterParallelBatchDims(*instruction, call_graph); if (scatter_parallel_dims) { changed |= InferScatterParallelShardingFromOperands( instruction, *scatter_parallel_dims, may_combine_partial_sharding); } for (int64_t i = 0; i != operand_count; ++i) { if (hlo_sharding_util::IsSpatiallyPartitioned(scatter_updates[i])) { auto maybe_from_update = hlo_sharding_util::ScatterOutputShardingFromUpdate( scatter_updates[i]->sharding(), scatter); if (maybe_from_update) { changed |= MaybeImproveInstructionSubSharding( std::move(*maybe_from_update), instruction, {i}, may_combine_partial_sharding); } } } } else { for (int64_t i = 0; i != operand_count; ++i) { changed |= MaybeImproveInstructionSubSharding( HloSharding::Replicate(), instruction, {i}, may_combine_partial_sharding); } } return changed; } case HloOpcode::kWhile: { if (!instruction->operand(0)->has_sharding()) { return false; } auto sharding = instruction->operand(0)->sharding(); if (instruction->has_sharding()) { hlo_sharding_util::MergeSharding(instruction->sharding(), &sharding, may_combine_partial_sharding); } return MaybeImproveInstructionSharding(std::move(sharding), instruction, may_combine_partial_sharding); } case HloOpcode::kCustomCall: { HloSharding inferred_operand_sharding = HloSharding::Replicate(); if (auto* partitioner = GetCustomCallPartitioner(instruction->custom_call_target()); partitioner && partitioner->IsCustomCallShardable(instruction)) { if (auto sharding = partitioner->InferShardingFromOperands(instruction)) { inferred_operand_sharding = *sharding; } else { return false; } } else if (sharding_helper_->IsCustomCallShardable(instruction)) { if (auto sharding = sharding_helper_->InferShardingFromOperands(instruction)) { inferred_operand_sharding = *sharding; } else { return false; } } else { const HloInstruction* operand = PickRepresentativeOperand(instruction); if (!operand || !hlo_sharding_util::IsSpatiallyPartitioned(operand)) { return false; } inferred_operand_sharding = operand->sharding(); } return MaybeImproveInstructionSharding( inferred_operand_sharding, instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ComputeNonRootUsers(instruction) == 1); } default: { if (instruction->IsElementwise() && may_combine_partial_sharding) { bool changed = false; for (auto operand : instruction->operands()) { if (hlo_sharding_util::IsSpatiallyPartitioned(operand)) { if (instruction->opcode() == HloOpcode::kRng) { // Rng is considered elementwise but has operands with different // shapes. changed |= MaybeImproveInstructionSharding( hlo_sharding_util::ReplicateAllDataDims( operand->sharding(), instruction->shape().rank()), instruction, may_combine_partial_sharding, ComputeNonRootUsers(instruction) == 1); continue; } changed |= MaybeImproveInstructionSharding( operand->sharding(), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ instruction->operands().size() == 1 && ComputeNonRootUsers(instruction) == 1); } } return changed; } const HloInstruction* operand = PickRepresentativeOperand(instruction); if (!operand || !hlo_sharding_util::IsSpatiallyPartitioned(operand)) { return false; } return MaybeImproveInstructionSharding( operand->sharding(), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ComputeNonRootUsers(instruction) == 1); } } return false; } // NOLINT(readability/fn_size) auto get_maybe_tuple_sharding = [&](HloSharding sharding) { if (instruction->shape().IsArray()) { return sharding; } std::vector<HloSharding> tuple(instruction->shape().tuple_shapes_size(), std::move(sharding)); return HloSharding::Tuple(instruction->shape(), tuple); }; auto is_more_specific = [instruction](const HloSharding& operand_sharding, const HloSharding& existing) { // If the instruction originally had no sharding, always prefer operand // sharding. return !instruction->has_sharding() || hlo_sharding_util::IsShardingMoreSpecific(operand_sharding, existing); }; VLOG(2) << "Not applying sharding to reduce window because dilatation " VLOG(2) << "Not applying sharding to select-and-scatter because " bool ShardingPropagation::InferShardingFromUsers( HloInstruction* instruction, const ShardingPropagation::ComputationMap& computation_map, int64_t aggressiveness, bool is_spmd, const CustomCallShardingHelper* sharding_helper, const CallGraph& call_graph) { if (aggressiveness < 2 && instruction->opcode() == HloOpcode::kBroadcast) { return false; } // Do not change manual sharding. if (instruction->has_sharding() && instruction->sharding().IsManual()) { return false; } // Propagate manual sharding. if (!instruction->has_sharding() || instruction->sharding().IsTileMaximal()) { for (const HloInstruction* user : instruction->users()) { if (!user->has_sharding() || user->IsCustomCall("SPMDFullToShardShape")) continue; if (instruction->shape().IsArray() && user->sharding().IsManual()) { instruction->set_sharding( HloSharding::Manual(user->sharding().metadata())); return true; } else { std::optional<HloSharding> user_sharding = ShardingPropagation::GetShardingFromUser( *instruction, *user, aggressiveness, is_spmd, call_graph, sharding_helper); if (user_sharding && user_sharding->IsManual()) { instruction->set_sharding(std::move(*user_sharding)); return true; } } } } if (!SupportSpatialPartitioning( instruction, computation_map, is_spmd, /*allow_spmd_sharding_propagation_to_output=*/false, allow_spmd_sharding_propagation_to_parameters_, sharding_helper)) { return false; } bool improved_sharding = false; const bool may_combine_partial_sharding = is_spmd && aggressiveness > 0; for (const HloInstruction* user : instruction->users()) { std::optional<HloSharding> user_sharding = ShardingPropagation::GetShardingFromUser(*instruction, *user, aggressiveness, is_spmd, call_graph, sharding_helper); if (user_sharding && instruction->opcode() == HloOpcode::kCustomCall) { if (auto* partitioner = GetCustomCallPartitioner(instruction->custom_call_target())) { if (partitioner->IsCustomCallShardable(instruction)) { user_sharding = partitioner->PropagateUserSharding(instruction, user, *user_sharding); } } else if (sharding_helper->IsCustomCallShardable(instruction)) { user_sharding = sharding_helper->PropagateUserSharding( instruction, user, *user_sharding); } } if (user_sharding) { improved_sharding |= MaybeImproveInstructionSharding( std::move(*user_sharding), instruction, may_combine_partial_sharding); } } return improved_sharding; } absl::StatusOr<bool> ShardingPropagation::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { // Register custom-call partitioner for SharBarrierFrom and ShardBarrierTo. ABSL_CONST_INIT static absl::once_flag did_registration; absl::call_once(did_registration, [] { RegisterCustomCallPartitioner( spmd::kShardBarrierFrom, std::make_unique<spmd::ShardBarrierFromPartitioner>()); RegisterCustomCallPartitioner( spmd::kShardBarrierTo, std::make_unique<spmd::ShardBarrierToPartitioner>()); }); std::optional<absl::flat_hash_map<const HloInstruction*, HloSharding>> original_sharding; bool any_changed = false; // Preprocessing for CSE prevention propagation: record the original shardings // so that we can revert to them at the end, and only keep those on CSE // prevention instructions. if (cse_prevention_only_) { original_sharding.emplace(); for (auto computation : module->computations(execution_threads)) { for (auto instruction : computation->instructions()) { if (instruction->has_sharding()) { original_sharding->emplace(instruction, instruction->sharding()); } } } } else { // The current pass is not for CSE prevention, but we remove the shardings // added by previous passes for CSE prevention. for (auto computation : module->computations(execution_threads)) { for (auto instruction : computation->instructions()) { if (instruction->has_sharding() && IsCSEPreventionSharding(instruction->sharding())) { instruction->clear_sharding(); any_changed = true; } } } } any_changed |= propagate_metadata_ ? AssignShardingMetadata(module, execution_threads) : RemoveShardingMetadata(module, execution_threads); absl::flat_hash_map<const HloInstruction*, std::vector<int64_t>> unspecified_dims; std::vector<HloSharding> saved_root_shardings; absl::flat_hash_map<int64_t, HloSharding> saved_parameter_shardings; absl::flat_hash_map<HloInstruction*, int64_t> instruction_to_shard_group_id; absl::flat_hash_map<int64_t, absl::flat_hash_set<HloInstruction*>> shard_group_id_to_shard_as_group; absl::flat_hash_map<int64_t, absl::flat_hash_set<HloInstruction*>> shard_group_id_to_shard_like_group; TF_ASSIGN_OR_RETURN( bool changed, ProcessShardingInstruction( module, execution_threads, !cse_prevention_only_, &unspecified_dims, allow_spmd_sharding_propagation_to_output_ ? &saved_root_shardings : nullptr, allow_spmd_sharding_propagation_to_parameters_ ? &saved_parameter_shardings : nullptr, &instruction_to_shard_group_id, &shard_group_id_to_shard_as_group, &shard_group_id_to_shard_like_group, &allow_spmd_sharding_propagation_to_parameters_vector_)); any_changed |= changed; for (const auto& [shard_group_id, shard_as_group] : shard_group_id_to_shard_as_group) { VLOG(5) << "Shard-As group " << shard_group_id << " contains:"; for (auto instruction : shard_as_group) { VLOG(5) << " " << instruction->ToString(); } } for (const auto& [shard_group_id, shard_like_group] : shard_group_id_to_shard_like_group) { VLOG(5) << "Shard-Like group " << shard_group_id << " contains:"; for (auto instruction : shard_like_group) { VLOG(5) << " " << instruction->ToString(); } } // Check sizes of the given allow_spmd_sharding_propagation vectors if (allow_spmd_sharding_propagation_to_output_) { CHECK(!module->entry_computation()->root_instruction()->has_sharding() || allow_spmd_sharding_propagation_to_output_vector_.size() == 1 || module->entry_computation() ->root_instruction() ->sharding() .tuple_elements() .size() == allow_spmd_sharding_propagation_to_output_vector_.size()) << "allow-spmd-sharding-propagation-to-output-vector's size can be " "either 1 or the number of elements in the root tuple of entry " "computation."; } if (allow_spmd_sharding_propagation_to_parameters_) { auto is_same_sized_tuple = [](HloModule* module, int64_t size) { if (module->entry_computation()->num_parameters() != 1) { return false; } HloInstruction* param = module->entry_computation()->parameter_instruction(0); return param->shape().IsTuple() && size == param->shape().tuple_shapes_size(); }; auto size = allow_spmd_sharding_propagation_to_parameters_vector_.size(); CHECK(size == 1 || size == module->entry_computation()->num_parameters() || is_same_sized_tuple(module, size)) << "allow-spmd-sharding-propagation-to-parameters-vector's size can be " "either 1 or the number of parameters in the entry computation."; } // Association of partitionable embedded computations with their parent // instruction. ComputationMap computation_map; // Instructions that are related through a computation and need to share the // same sharding. auto get_related_instructions = [this](HloInstruction* inst) { if (inst->opcode() == HloOpcode::kWhile) { return std::vector<HloInstruction*>{ inst, inst->while_body()->root_instruction(), inst->while_body()->parameter_instruction(0), inst->while_condition()->parameter_instruction(0)}; } else if (inst->opcode() == HloOpcode::kConditional) { const auto& called_computations = inst->called_computations(); std::vector<HloInstruction*> comps; comps.reserve(called_computations.size() + 1); comps.push_back(inst); for (HloComputation* c : called_computations) { comps.push_back(c->root_instruction()); } return comps; } else if (inst->opcode() == HloOpcode::kCustomCall) { if (sharding_helper_ && sharding_helper_->IsCustomCallShardable(inst)) { return sharding_helper_->GetRelatedInstructions(inst); } else { return std::vector<HloInstruction*>{}; } } else if (inst->opcode() == HloOpcode::kCall) { HloComputation* callee = inst->called_computations().front(); return std::vector<HloInstruction*>{inst, callee->root_instruction()}; } else { CHECK(false); } }; // If instruction is a while, or the root or a parameter of a while body, // then propagate its sharding to the while instruction, to its body root, // and to its condition parameter. std::function<void(HloInstruction*, absl::flat_hash_set<HloInstruction*>*)> maybe_computation_propagation = [&](HloInstruction* instruction, absl::flat_hash_set<HloInstruction*>* changed) { auto propagate_to_instruction = [&](HloInstruction* search_inst) { auto related_instructions = get_related_instructions(search_inst); if (absl::c_count(related_instructions, instruction)) { for (HloInstruction* inst : related_instructions) { if (!inst->has_sharding() || inst->sharding() != instruction->sharding()) { VLOG(2) << "Add computation sharding: " << inst->name() << " " << instruction->sharding().ToString(); inst->copy_sharding(instruction); changed->insert(inst); maybe_computation_propagation(inst, changed); } } } }; if (instruction->opcode() == HloOpcode::kConditional || instruction->opcode() == HloOpcode::kWhile || instruction->opcode() == HloOpcode::kCustomCall || instruction->opcode() == HloOpcode::kCall) { propagate_to_instruction(instruction); } if (instruction->opcode() == HloOpcode::kParameter || instruction->parent()->root_instruction() == instruction) { auto it = computation_map.find(instruction->parent()); if (it != computation_map.end()) { propagate_to_instruction(it->second); } } }; for (auto computation : module->computations(execution_threads)) { for (auto instruction : computation->instructions()) { if (instruction->opcode() == HloOpcode::kWhile) { TF_RETURN_IF_ERROR( CheckAndUpdateDeviceAssignmentsInWhileBody(instruction)); } } } // Populate computation_map in order to associate while bodies to their // while instructions. for (auto computation : module->computations(execution_threads)) { for (auto instruction : computation->instructions()) { if (instruction->opcode() == HloOpcode::kWhile || instruction->opcode() == HloOpcode::kConditional || instruction->opcode() == HloOpcode::kCall) { // Check if any of the related instructions has sharding, in which case // propagate it to the other instructions, so they all share the same // sharding, in case the user didn't shard all of them. We don't check // that user shardings are consistent, because such check is already // done by HLO verifier. const HloInstruction* sharded_inst = nullptr; auto related_instructions = get_related_instructions(instruction); for (auto inst : related_instructions) { if (inst->has_sharding()) { sharded_inst = inst; break; } } if (sharded_inst != nullptr) { // Set the same sharding to all the other related instructions. for (auto inst : related_instructions) { inst->copy_sharding(sharded_inst); } } if (instruction->opcode() == HloOpcode::kWhile) { computation_map[instruction->while_body()] = instruction; } else { for (HloComputation* c : instruction->called_computations()) { computation_map[c] = instruction; } } } } } // Collect all pre-sharded instructions as we aren't allowed to modify their // sharding. absl::flat_hash_set<const HloInstruction*> provided_shardings; for (const HloComputation* computation : module->computations(execution_threads)) { for (const HloInstruction* inst : computation->instructions()) { if (inst->has_sharding() && inst != module->entry_computation()->root_instruction() && inst->opcode() != HloOpcode::kParameter && !inst->sharding().IsUnknown()) { provided_shardings.insert(inst); } } } if (!allow_spmd_sharding_propagation_to_output_ && (!module->entry_computation()->root_instruction()->has_sharding() || !module->entry_computation() ->root_instruction() ->sharding() .IsUnknown())) { // Consider the root instruction of the entry module as one with provided // sharding as its sharding have to match with the one expected by the host. provided_shardings.insert(module->entry_computation()->root_instruction()); } if (!allow_spmd_sharding_propagation_to_parameters_) { for (auto param : module->entry_computation()->parameter_instructions()) { if (param->has_sharding() && !param->sharding().IsUnknown()) { provided_shardings.insert(param); } } } // Replace all unknown shardings with replicated sharding for propagation. for (HloComputation* computation : module->computations(execution_threads)) { auto instructions = computation->MakeInstructionPostOrder(); for (auto it = instructions.rbegin(); it != instructions.rend(); ++it) { HloInstruction* instruction = *it; if (instruction->has_sharding() && instruction->sharding().IsUnknown()) { instruction->set_sharding( HloSharding::Replicate(instruction->sharding().metadata())); } } } // Iterate to a fixpoint that is guaranteed to be reached because we only // strictly improve the sharding of the graph and it can't be improved // indefinitely. int64_t iterations = 0; std::unique_ptr<CallGraph> call_graph = CallGraph::Build(module); auto run_to_fix_point = [&](int64_t aggressiveness, bool propagate_shard_group) { absl::flat_hash_set<const HloInstruction*> already_inferred_from_shard_group; absl::flat_hash_set<const HloInstruction*> already_inferred_from_operands; absl::flat_hash_set<const HloInstruction*> already_inferred_from_users; bool changed_last_iter = true; const bool may_merge_partial = is_spmd_ && aggressiveness > 0; while (changed_last_iter) { changed_last_iter = false; int64_t inferred_from_shard_group_counter = 0; int64_t inferred_from_operand_counter = 0; int64_t inferred_from_user_counter = 0; int64_t instruction_counter = 0; int64_t already_sharded_counter = 0; for (const HloComputation* computation : module->computations(execution_threads)) { VLOG(2) << "Consider computation: " << computation->name(); std::vector<HloInstruction*> instructions = computation->MakeInstructionPostOrder(); instruction_counter += instructions.size(); already_sharded_counter += absl::c_count_if( instructions, [](const HloInstruction* inst) { return inst->has_sharding(); }); auto clear_cache = [&](HloInstruction* hlo, HloInstruction* hlo_for_users = nullptr) { for (auto operand : hlo->operands()) { already_inferred_from_users.erase(operand); } if (hlo_for_users == nullptr) { hlo_for_users = hlo; } for (auto user : hlo_for_users->users()) { already_inferred_from_operands.erase(user); // If the user has called computations, then the parameter // instructions of these called computations are also removed from // already_inferred_from_operands. for (auto c : user->called_computations()) { for (auto parameter : c->parameter_instructions()) { already_inferred_from_operands.erase(parameter); } } } if (instruction_to_shard_group_id.contains(hlo)) { const int64_t shard_group_id = instruction_to_shard_group_id.at(hlo); const absl::flat_hash_set<HloInstruction*>& shard_group = shard_group_id_to_shard_as_group.contains(shard_group_id) ? shard_group_id_to_shard_as_group.at(shard_group_id) : shard_group_id_to_shard_like_group.at(shard_group_id); for (HloInstruction* member : shard_group) { if (member != hlo) { already_inferred_from_shard_group.erase(member); } } } }; // 1. Iterate the shard groups to take shardings from instructions of // the same group. if (propagate_shard_group) { for (HloInstruction* instruction : instructions) { if (already_inferred_from_shard_group.contains(instruction)) { continue; } if (!instruction_to_shard_group_id.contains(instruction)) { continue; } const int64_t shard_group_id = instruction_to_shard_group_id.at(instruction); const absl::flat_hash_set<HloInstruction*>& shard_group = shard_group_id_to_shard_as_group.contains(shard_group_id) ? shard_group_id_to_shard_as_group.at(shard_group_id) : shard_group_id_to_shard_like_group.at(shard_group_id); if (provided_shardings.contains(instruction)) { if (!may_merge_partial) { continue; } auto it = unspecified_dims.find(instruction); if (it != unspecified_dims.end() && InferUnspecifiedDimsFromShardGroup(instruction, it->second, shard_group)) { ++inferred_from_shard_group_counter; VLOG(2) << "Refined partial sharding (shard group): " << instruction->ToString(); clear_cache(instruction); already_inferred_from_shard_group.insert(instruction); changed_last_iter = true; } continue; } already_inferred_from_shard_group.insert(instruction); if (InferShardingFromShardGroup(instruction, computation_map, aggressiveness, shard_group)) { ++inferred_from_shard_group_counter; any_changed = true; VLOG(2) << "Add sharding (shard group): " << instruction->ToString(); absl::flat_hash_set<HloInstruction*> changed_in_comp_prop; maybe_computation_propagation(instruction, &changed_in_comp_prop); clear_cache(instruction); for (auto hlo : changed_in_comp_prop) { clear_cache(hlo); } changed_last_iter = true; } } } // 2. Iterate the HLO graph in post order taking shardings from // operands. for (HloInstruction* instruction : instructions) { if (already_inferred_from_operands.contains(instruction)) { continue; } if (provided_shardings.contains(instruction)) { if (!may_merge_partial) { continue; } auto it = unspecified_dims.find(instruction); HloInstruction* man_conversion_op_after; if (it != unspecified_dims.end() && InferUnspecifiedDimsFromOperand(instruction, it->second, &man_conversion_op_after)) { ++inferred_from_operand_counter; VLOG(2) << "Refined partial sharding (forward-pass): " << instruction->ToString(); clear_cache(instruction, man_conversion_op_after); already_inferred_from_operands.insert(instruction); changed_last_iter = true; } continue; } already_inferred_from_operands.insert(instruction); if (InferShardingFromOperands(instruction, computation_map, aggressiveness, *call_graph, execution_threads)) { ++inferred_from_operand_counter; any_changed = true; VLOG(2) << "Add sharding (forward-pass): " << instruction->ToString(); absl::flat_hash_set<HloInstruction*> changed_in_comp_prop; maybe_computation_propagation(instruction, &changed_in_comp_prop); clear_cache(instruction); for (auto hlo : changed_in_comp_prop) { clear_cache(hlo); } changed_last_iter = true; } } // 3. Iterate the HLO graph in reverse post order taking shardings from // users. for (auto it = instructions.rbegin(); it != instructions.rend(); ++it) { if ((*it)->IsCustomCall("SPMDFullToShardShape") || (*it)->IsCustomCall("SPMDShardToFullShape")) { // The manual conversion op is processed together with the sharding // op before it. If the conversion op is removed from cache, the // sharding op should also be removed. if (!already_inferred_from_users.contains(*it)) { already_inferred_from_users.erase((*it)->operand(0)); } } if (already_inferred_from_users.contains(*it)) { continue; } if (provided_shardings.contains(*it)) { if (!may_merge_partial) { continue; } auto uit = unspecified_dims.find(*it); HloInstruction* man_conversion_op_after; if (uit != unspecified_dims.end() && InferUnspecifiedDimsFromUsers( *it, uit->second, aggressiveness, is_spmd_, &man_conversion_op_after, *call_graph)) { ++inferred_from_user_counter; VLOG(2) << "Refined partial sharding (backward-pass): " << (*it)->ToString(); clear_cache(*it, man_conversion_op_after); already_inferred_from_users.insert(*it); if (man_conversion_op_after != nullptr) { already_inferred_from_users.insert(man_conversion_op_after); } changed_last_iter = true; } continue; } already_inferred_from_users.insert(*it); if (InferShardingFromUsers(*it, computation_map, aggressiveness, is_spmd_, sharding_helper_.get(), *call_graph)) { ++inferred_from_user_counter; any_changed = true; VLOG(2) << "Add sharding (backward-pass): " << (*it)->ToString(); absl::flat_hash_set<HloInstruction*> changed_in_comp_prop; maybe_computation_propagation(*it, &changed_in_comp_prop); clear_cache(*it); for (auto hlo : changed_in_comp_prop) { clear_cache(hlo); } changed_last_iter = true; } } } VLOG(1) << "Sharding propagation iteration " << iterations << ";" << "\n total instructions: " << instruction_counter << "\n instructions already sharded: " << already_sharded_counter << "\n shardings inferred from shard group: " << inferred_from_shard_group_counter << "\n shardings inferred from operands: " << inferred_from_operand_counter << "\n shardings inferred from users: " << inferred_from_user_counter << "\n aggressiveness: " << aggressiveness; ++iterations; } return absl::OkStatus(); }; for (int64_t aggressiveness = 0; aggressiveness < 4; ++aggressiveness) { TF_RETURN_IF_ERROR( run_to_fix_point(aggressiveness, /*propagate_shard_group=*/true)); } // Align the shardings from the same shard_as group so that they will adopt // the same sharding. for (const auto& [shard_as_group_id, shard_as_group] : shard_group_id_to_shard_as_group) { // If all the inferred shardings of the instructions from the same shard // group are compatible with each other, then we will merge all of them to // get the most specific sharding. If some of them are not compatible, then // it will just choose the a random sharding among them(say the first one), // with the guarantee that the defaultly chosen sharding will not be from a // ShardBarrierFrom op if there is one within the ShardAs group. HloSharding default_sharding = HloSharding::Replicate(); std::vector<HloSharding> shardings; for (HloInstruction* instruction : shard_as_group) { if (instruction->has_sharding()) { shardings.push_back(instruction->sharding()); if (!instruction->IsCustomCall(spmd::kShardBarrierFrom) && default_sharding.IsReplicated()) { default_sharding = instruction->sharding(); } } } HloSharding common_sharding = hlo_sharding_util::FindCommonSharding(shardings, default_sharding); VLOG(2) << "Aligning shard group: " << shard_as_group_id << " to sharding:" << common_sharding.ToString(); for (HloInstruction* member : shard_as_group) { if (member->IsCustomCall(spmd::kShardBarrierTo)) { continue; } if (provided_shardings.contains(member)) { auto it = unspecified_dims.find(member); if (it != unspecified_dims.end()) { HloSharding partial_replicated = hlo_sharding_util::PartiallyReplicateTiledShardingOnAllDimsExcept( common_sharding, it->second); HloSharding sharding = member->sharding(); if (hlo_sharding_util::MergeShardingIfCompatible( partial_replicated, sharding.NumTiles() + 1, &sharding)) { member->set_sharding(sharding); } } } member->set_sharding(common_sharding); } } // If a ShardBarrierFrom custom-call op is in a shard as group, and relay // the shard as sharding to its original op, do not relay shardings for // ShardbarrierTo op. Then run sharding propagation once more at highest // aggressiveness without propagating shard group. for (HloComputation* computation : module->computations(execution_threads)) { for (HloInstruction* instruction : computation->instructions()) { if (instruction->IsCustomCall(spmd::kShardBarrierFrom) && instruction_to_shard_group_id.contains(instruction) && shard_group_id_to_shard_as_group.contains( instruction_to_shard_group_id.at(instruction))) { HloSharding sharding = instruction->sharding(); hlo_sharding_util::MergeShardingIfCompatible( instruction->mutable_operand(0)->sharding(), sharding.NumTiles(), &sharding); instruction->mutable_operand(0)->set_sharding(std::move(sharding)); } } } TF_RETURN_IF_ERROR( run_to_fix_point(/*aggressiveness=*/3, /*propagate_shard_group=*/false)); // Post-process to remove all "shard-barrier-from" and "shard-barrier-to" // custom-calls. for (HloComputation* computation : module->computations(execution_threads)) { for (HloInstruction* instruction : computation->instructions()) { // If a ShardBarrierFrom custom-call op is in a shard as group, and relay // the shard as sharding to its original op, do not relay shardings for // ShardbarrierTo op. if (instruction->IsCustomCall(spmd::kShardBarrierFrom) && instruction_to_shard_group_id.contains(instruction) && shard_group_id_to_shard_as_group.contains( instruction_to_shard_group_id.at(instruction))) { HloSharding sharding = instruction->sharding(); hlo_sharding_util::MergeShardingIfCompatible( instruction->mutable_operand(0)->sharding(), sharding.NumTiles(), &sharding); instruction->mutable_operand(0)->set_sharding(std::move(sharding)); } if (instruction->IsCustomCall(spmd::kShardBarrierFrom) || instruction->IsCustomCall(spmd::kShardBarrierTo)) { TF_ASSIGN_OR_RETURN(std::ignore, computation->ReplaceInstruction( instruction, instruction->mutable_operand(0), /*preserve_sharding=*/false, /*relay_control_dependency=*/false, /*remove_unused_operands=*/false)); } } } // Post-process for CSE prevention. if (cse_prevention_only_) { for (auto computation : module->computations(execution_threads)) { for (auto instruction : computation->instructions()) { if (!instruction->has_sharding()) { continue; } if (IsCSEPreventionTarget(instruction) && instruction->has_sharding()) { if (!(*original_sharding).contains(instruction)) { // Mark the propagated sharding as for CSE prevention. instruction->set_sharding( SetCSEPreventionSharding(instruction->sharding())); } continue; } auto it = (*original_sharding).find(instruction); if (it != (*original_sharding).end()) { // Revert sharding. instruction->set_sharding(it->second); } else { // Clear sharding. instruction->clear_sharding(); } } } } HloInstruction* root_instruction = module->entry_computation()->root_instruction(); if (saved_root_shardings.size() == allow_spmd_sharding_propagation_to_output_vector_.size() && root_instruction->has_sharding()) { HloSharding root_sharding = root_instruction->sharding(); for (int i = 0; i < saved_root_shardings.size(); ++i) { if (!allow_spmd_sharding_propagation_to_output_vector_[i] && !saved_root_shardings[i].IsUnknown()) { root_sharding.tuple_elements()[i] = saved_root_shardings[i]; } } root_instruction->set_sharding(std::move(root_sharding)); } auto params = module->entry_computation()->parameter_instructions(); if (allow_spmd_sharding_propagation_to_parameters_) { if (allow_spmd_sharding_propagation_to_parameters_vector_.size() == params.size()) { for (int64_t i = 0; i < params.size(); ++i) { if (!allow_spmd_sharding_propagation_to_parameters_vector_[i]) { if (saved_parameter_shardings.contains(i) && !saved_parameter_shardings.at(i).IsUnknown()) { params[i]->set_sharding(saved_parameter_shardings.at(i)); } else { params[i]->clear_sharding(); } } } } else if (params.size() == 1 && saved_parameter_shardings.size() == 1 && params[0]->shape().IsTuple() && params[0]->shape().tuple_shapes_size() == allow_spmd_sharding_propagation_to_parameters_vector_ .size()) { // There is a single parameter which is a tuple with many elements. HloSharding param_sharding = params[0]->sharding(); for (int64_t i = 0; i < params[0]->shape().tuple_shapes_size(); ++i) { HloSharding saved_subsharding = saved_parameter_shardings.at(0).GetSubSharding(params[0]->shape(), {i}); if (!allow_spmd_sharding_propagation_to_parameters_vector_[i] && !saved_subsharding.IsUnknown()) { param_sharding.tuple_elements()[i] = saved_subsharding; } } params[0]->set_sharding(std::move(param_sharding)); } } // Replicate the parameter/output sharding if the propagated sharding does not // evenly partition the parameter/output. std::function<bool(const Shape&, const HloSharding&)> evenly_partitions = [&evenly_partitions](const Shape& shape, const HloSharding& sharding) -> bool { if (!sharding.IsTiled()) { return true; } if (sharding.IsTileMaximal()) { return sharding.IsReplicated(); } if (sharding.IsTuple()) { for (int64_t i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { if (!evenly_partitions(ShapeUtil::GetTupleElementShape(shape, i), sharding.GetSubSharding(shape, {i}))) { return false; } } } for (int64_t i = 0; i < shape.dimensions_size(); ++i) { if (shape.dimensions(i) % sharding.tile_assignment().dim(i) != 0) { return false; } } return true; }; if (allow_spmd_sharding_propagation_to_output_ && root_instruction->has_sharding()) { if (root_instruction->shape().IsTuple() && allow_spmd_sharding_propagation_to_output_vector_.size() == root_instruction->shape().tuple_shapes_size()) { // The output shape is a tuple and sharding propagation is allowed for at // least one of its elements. HloSharding root_sharding = root_instruction->sharding(); for (int64_t i = 0; i < root_instruction->shape().tuple_shapes_size(); ++i) { if (allow_spmd_sharding_propagation_to_output_vector_[i] && !evenly_partitions(root_instruction->shape().tuple_shapes(i), root_sharding.tuple_elements()[i])) { root_sharding.tuple_elements()[i] = HloSharding::Replicate(); } } root_instruction->set_sharding(std::move(root_sharding)); } else if (!root_instruction->shape().IsTuple()) { // The output shape is not tuple and sharding propagation is allowed. if (!evenly_partitions(root_instruction->shape(), root_instruction->sharding())) { root_instruction->set_sharding(HloSharding::Replicate()); } } } if (allow_spmd_sharding_propagation_to_parameters_) { // Sharding propagation is allowed for at least one parameter. if (allow_spmd_sharding_propagation_to_parameters_vector_.size() == params.size()) { for (int64_t i = 0; i < params.size(); ++i) { if (params[i]->has_sharding() && allow_spmd_sharding_propagation_to_parameters_vector_[i] && !evenly_partitions(params[i]->shape(), params[i]->sharding())) { params[i]->set_sharding(HloSharding::Replicate()); } } } else if (params.size() == 1 && params[0]->shape().IsTuple() && params[0]->has_sharding() && params[0]->shape().tuple_shapes_size() == allow_spmd_sharding_propagation_to_parameters_vector_ .size()) { HloSharding param_sharding = params[0]->sharding(); for (int64_t i = 0; i < params[0]->shape().tuple_shapes_size(); ++i) { if (allow_spmd_sharding_propagation_to_parameters_vector_[i] && !evenly_partitions( ShapeUtil::GetSubshapeOneIndex(params[0]->shape(), i), params[0]->sharding().GetSubSharding(params[0]->shape(), {i}))) { param_sharding.tuple_elements()[i] = HloSharding::Replicate(); } } params[0]->set_sharding(std::move(param_sharding)); } } TF_RETURN_IF_ERROR( hlo_sharding_util::CanonicalizeLayoutAfterShardingPropagation( module, allow_spmd_sharding_propagation_to_output_, allow_spmd_sharding_propagation_to_parameters_)); VLOG(1) << "Sharding propagation completed after " << iterations << " iterations"; return any_changed; } absl::call_once(did_registration, [] { RegisterCustomCallPartitioner( spmd::kShardBarrierFrom, std::make_unique<spmd::ShardBarrierFromPartitioner>()); RegisterCustomCallPartitioner( spmd::kShardBarrierTo, std::make_unique<spmd::ShardBarrierToPartitioner>()); }); VLOG(5) << "Shard-As group " << shard_group_id << " contains:"; VLOG(5) << " " << instruction->ToString(); VLOG(5) << "Shard-Like group " << shard_group_id << " contains:"; VLOG(5) << " " << instruction->ToString(); auto is_same_sized_tuple = [](HloModule* module, int64_t size) { if (module->entry_computation()->num_parameters() != 1) { return false; } HloInstruction* param = module->entry_computation()->parameter_instruction(0); return param->shape().IsTuple() && size == param->shape().tuple_shapes_size(); }; auto get_related_instructions = [this](HloInstruction* inst) { if (inst->opcode() == HloOpcode::kWhile) { return std::vector<HloInstruction*>{ inst, inst->while_body()->root_instruction(), inst->while_body()->parameter_instruction(0), inst->while_condition()->parameter_instruction(0)}; } else if (inst->opcode() == HloOpcode::kConditional) { const auto& called_computations = inst->called_computations(); std::vector<HloInstruction*> comps; comps.reserve(called_computations.size() + 1); comps.push_back(inst); for (HloComputation* c : called_computations) { comps.push_back(c->root_instruction()); } return comps; } else if (inst->opcode() == HloOpcode::kCustomCall) { if (sharding_helper_ && sharding_helper_->IsCustomCallShardable(inst)) { return sharding_helper_->GetRelatedInstructions(inst); } else { return std::vector<HloInstruction*>{}; } } else if (inst->opcode() == HloOpcode::kCall) { HloComputation* callee = inst->called_computations().front(); return std::vector<HloInstruction*>{inst, callee->root_instruction()}; } else { CHECK(false); } }; [&](HloInstruction* instruction, absl::flat_hash_set<HloInstruction*>* changed) { auto propagate_to_instruction = [&](HloInstruction* search_inst) { auto related_instructions = get_related_instructions(search_inst); if (absl::c_count(related_instructions, instruction)) { for (HloInstruction* inst : related_instructions) { if (!inst->has_sharding() || inst->sharding() != instruction->sharding()) { VLOG(2) << "Add computation sharding: " << inst->name() << " " << instruction->sharding().ToString(); inst->copy_sharding(instruction); changed->insert(inst); maybe_computation_propagation(inst, changed); } } } }; if (instruction->opcode() == HloOpcode::kConditional || instruction->opcode() == HloOpcode::kWhile || instruction->opcode() == HloOpcode::kCustomCall || instruction->opcode() == HloOpcode::kCall) { propagate_to_instruction(instruction); } if (instruction->opcode() == HloOpcode::kParameter || instruction->parent()->root_instruction() == instruction) { auto it = computation_map.find(instruction->parent()); if (it != computation_map.end()) { propagate_to_instruction(it->second); } } }; auto propagate_to_instruction = [&](HloInstruction* search_inst) { auto related_instructions = get_related_instructions(search_inst); if (absl::c_count(related_instructions, instruction)) { for (HloInstruction* inst : related_instructions) { if (!inst->has_sharding() || inst->sharding() != instruction->sharding()) { VLOG(2) << "Add computation sharding: " << inst->name() << " " << instruction->sharding().ToString(); inst->copy_sharding(instruction); changed->insert(inst); maybe_computation_propagation(inst, changed); } } } }; VLOG(2) << "Add computation sharding: " << inst->name() auto run_to_fix_point = [&](int64_t aggressiveness, bool propagate_shard_group) { absl::flat_hash_set<const HloInstruction*> already_inferred_from_shard_group; absl::flat_hash_set<const HloInstruction*> already_inferred_from_operands; absl::flat_hash_set<const HloInstruction*> already_inferred_from_users; bool changed_last_iter = true; const bool may_merge_partial = is_spmd_ && aggressiveness > 0; while (changed_last_iter) { changed_last_iter = false; int64_t inferred_from_shard_group_counter = 0; int64_t inferred_from_operand_counter = 0; int64_t inferred_from_user_counter = 0; int64_t instruction_counter = 0; int64_t already_sharded_counter = 0; for (const HloComputation* computation : module->computations(execution_threads)) { VLOG(2) << "Consider computation: " << computation->name(); std::vector<HloInstruction*> instructions = computation->MakeInstructionPostOrder(); instruction_counter += instructions.size(); already_sharded_counter += absl::c_count_if( instructions, [](const HloInstruction* inst) { return inst->has_sharding(); }); auto clear_cache = [&](HloInstruction* hlo, HloInstruction* hlo_for_users = nullptr) { for (auto operand : hlo->operands()) { already_inferred_from_users.erase(operand); } if (hlo_for_users == nullptr) { hlo_for_users = hlo; } for (auto user : hlo_for_users->users()) { already_inferred_from_operands.erase(user); // If the user has called computations, then the parameter // instructions of these called computations are also removed from // already_inferred_from_operands. for (auto c : user->called_computations()) { for (auto parameter : c->parameter_instructions()) { already_inferred_from_operands.erase(parameter); } } } if (instruction_to_shard_group_id.contains(hlo)) { const int64_t shard_group_id = instruction_to_shard_group_id.at(hlo); const absl::flat_hash_set<HloInstruction*>& shard_group = shard_group_id_to_shard_as_group.contains(shard_group_id) ? shard_group_id_to_shard_as_group.at(shard_group_id) : shard_group_id_to_shard_like_group.at(shard_group_id); for (HloInstruction* member : shard_group) { if (member != hlo) { already_inferred_from_shard_group.erase(member); } } } }; // 1. Iterate the shard groups to take shardings from instructions of // the same group. if (propagate_shard_group) { for (HloInstruction* instruction : instructions) { if (already_inferred_from_shard_group.contains(instruction)) { continue; } if (!instruction_to_shard_group_id.contains(instruction)) { continue; } const int64_t shard_group_id = instruction_to_shard_group_id.at(instruction); const absl::flat_hash_set<HloInstruction*>& shard_group = shard_group_id_to_shard_as_group.contains(shard_group_id) ? shard_group_id_to_shard_as_group.at(shard_group_id) : shard_group_id_to_shard_like_group.at(shard_group_id); if (provided_shardings.contains(instruction)) { if (!may_merge_partial) { continue; } auto it = unspecified_dims.find(instruction); if (it != unspecified_dims.end() && InferUnspecifiedDimsFromShardGroup(instruction, it->second, shard_group)) { ++inferred_from_shard_group_counter; VLOG(2) << "Refined partial sharding (shard group): " << instruction->ToString(); clear_cache(instruction); already_inferred_from_shard_group.insert(instruction); changed_last_iter = true; } continue; } already_inferred_from_shard_group.insert(instruction); if (InferShardingFromShardGroup(instruction, computation_map, aggressiveness, shard_group)) { ++inferred_from_shard_group_counter; any_changed = true; VLOG(2) << "Add sharding (shard group): " << instruction->ToString(); absl::flat_hash_set<HloInstruction*> changed_in_comp_prop; maybe_computation_propagation(instruction, &changed_in_comp_prop); clear_cache(instruction); for (auto hlo : changed_in_comp_prop) { clear_cache(hlo); } changed_last_iter = true; } } } // 2. Iterate the HLO graph in post order taking shardings from // operands. for (HloInstruction* instruction : instructions) { if (already_inferred_from_operands.contains(instruction)) { continue; } if (provided_shardings.contains(instruction)) { if (!may_merge_partial) { continue; } auto it = unspecified_dims.find(instruction); HloInstruction* man_conversion_op_after; if (it != unspecified_dims.end() && InferUnspecifiedDimsFromOperand(instruction, it->second, &man_conversion_op_after)) { ++inferred_from_operand_counter; VLOG(2) << "Refined partial sharding (forward-pass): " << instruction->ToString(); clear_cache(instruction, man_conversion_op_after); already_inferred_from_operands.insert(instruction); changed_last_iter = true; } continue; } already_inferred_from_operands.insert(instruction); if (InferShardingFromOperands(instruction, computation_map, aggressiveness, *call_graph, execution_threads)) { ++inferred_from_operand_counter; any_changed = true; VLOG(2) << "Add sharding (forward-pass): " << instruction->ToString(); absl::flat_hash_set<HloInstruction*> changed_in_comp_prop; maybe_computation_propagation(instruction, &changed_in_comp_prop); clear_cache(instruction); for (auto hlo : changed_in_comp_prop) { clear_cache(hlo); } changed_last_iter = true; } } // 3. Iterate the HLO graph in reverse post order taking shardings from // users. for (auto it = instructions.rbegin(); it != instructions.rend(); ++it) { if ((*it)->IsCustomCall("SPMDFullToShardShape") || (*it)->IsCustomCall("SPMDShardToFullShape")) { // The manual conversion op is processed together with the sharding // op before it. If the conversion op is removed from cache, the // sharding op should also be removed. if (!already_inferred_from_users.contains(*it)) { already_inferred_from_users.erase((*it)->operand(0)); } } if (already_inferred_from_users.contains(*it)) { continue; } if (provided_shardings.contains(*it)) { if (!may_merge_partial) { continue; } auto uit = unspecified_dims.find(*it); HloInstruction* man_conversion_op_after; if (uit != unspecified_dims.end() && InferUnspecifiedDimsFromUsers( *it, uit->second, aggressiveness, is_spmd_, &man_conversion_op_after, *call_graph)) { ++inferred_from_user_counter; VLOG(2) << "Refined partial sharding (backward-pass): " << (*it)->ToString(); clear_cache(*it, man_conversion_op_after); already_inferred_from_users.insert(*it); if (man_conversion_op_after != nullptr) { already_inferred_from_users.insert(man_conversion_op_after); } changed_last_iter = true; } continue; } already_inferred_from_users.insert(*it); if (InferShardingFromUsers(*it, computation_map, aggressiveness, is_spmd_, sharding_helper_.get(), *call_graph)) { ++inferred_from_user_counter; any_changed = true; VLOG(2) << "Add sharding (backward-pass): " << (*it)->ToString(); absl::flat_hash_set<HloInstruction*> changed_in_comp_prop; maybe_computation_propagation(*it, &changed_in_comp_prop); clear_cache(*it); for (auto hlo : changed_in_comp_prop) { clear_cache(hlo); } changed_last_iter = true; } } } VLOG(1) << "Sharding propagation iteration " << iterations << ";" << "\n total instructions: " << instruction_counter << "\n instructions already sharded: " << already_sharded_counter << "\n shardings inferred from shard group: " << inferred_from_shard_group_counter << "\n shardings inferred from operands: " << inferred_from_operand_counter << "\n shardings inferred from users: " << inferred_from_user_counter << "\n aggressiveness: " << aggressiveness; ++iterations; } return absl::OkStatus(); }; VLOG(2) << "Consider computation: " << computation->name(); auto clear_cache = [&](HloInstruction* hlo, HloInstruction* hlo_for_users = nullptr) { for (auto operand : hlo->operands()) { already_inferred_from_users.erase(operand); } if (hlo_for_users == nullptr) { hlo_for_users = hlo; } for (auto user : hlo_for_users->users()) { already_inferred_from_operands.erase(user); // If the user has called computations, then the parameter // instructions of these called computations are also removed from // already_inferred_from_operands. for (auto c : user->called_computations()) { for (auto parameter : c->parameter_instructions()) { already_inferred_from_operands.erase(parameter); } } } if (instruction_to_shard_group_id.contains(hlo)) { const int64_t shard_group_id = instruction_to_shard_group_id.at(hlo); const absl::flat_hash_set<HloInstruction*>& shard_group = shard_group_id_to_shard_as_group.contains(shard_group_id) ? shard_group_id_to_shard_as_group.at(shard_group_id) : shard_group_id_to_shard_like_group.at(shard_group_id); for (HloInstruction* member : shard_group) { if (member != hlo) { already_inferred_from_shard_group.erase(member); } } } }; VLOG(2) << "Refined partial sharding (shard group): " VLOG(2) << "Add sharding (shard group): " VLOG(2) << "Refined partial sharding (forward-pass): " VLOG(2) << "Add sharding (forward-pass): " VLOG(2) << "Refined partial sharding (backward-pass): " VLOG(2) << "Add sharding (backward-pass): " << (*it)->ToString(); VLOG(1) << "Sharding propagation iteration " << iterations << ";" VLOG(2) << "Aligning shard group: " << shard_as_group_id [&evenly_partitions](const Shape& shape, const HloSharding& sharding) -> bool { if (!sharding.IsTiled()) { return true; } if (sharding.IsTileMaximal()) { return sharding.IsReplicated(); } if (sharding.IsTuple()) { for (int64_t i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { if (!evenly_partitions(ShapeUtil::GetTupleElementShape(shape, i), sharding.GetSubSharding(shape, {i}))) { return false; } } } for (int64_t i = 0; i < shape.dimensions_size(); ++i) { if (shape.dimensions(i) % sharding.tile_assignment().dim(i) != 0) { return false; } } return true; }; VLOG(1) << "Sharding propagation completed after " << iterations
#include "xla/service/sharding_propagation.h" #include <ostream> #include <string> #include <utility> #include <vector> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/log/check.h" #include "absl/log/log.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/ir/hlo_op_metadata.h" #include "xla/hlo/ir/hlo_sharding.h" #include "xla/hlo/transforms/hlo_constant_splitter.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/protobuf_util.h" #include "xla/service/hlo_dce.h" #include "xla/service/hlo_parser.h" #include "xla/tests/hlo_test_base.h" #include "xla/util.h" #include "xla/xla_data.pb.h" #include "tsl/platform/statusor.h" TEST_F(ShardingPropagationTest, ShardAsWithShardBarrier) { const char* const hlo_string = R"( HloModule pjit_f ENTRY main.11 { Arg_0.1 = bf16[384,1408]{1,0} parameter(0), sharding={devices=[1,16,512]<=[8,16,64]T(1,0,2) last_tile_dim_replicate} broadcast.4 = bf16[8,384,1408]{2,1,0} broadcast(Arg_0.1), dimensions={1,2} custom-call.5 = bf16[8,384,1408]{2,1,0} custom-call(broadcast.4), custom_call_target="Sharding", custom_call_has_side_effect=true, sharding={unknown shard_as 1} broadcast.2 = bf16[8,384,1408]{2,1,0} broadcast(Arg_0.1), dimensions={1,2} custom-call.3 = bf16[8,384,1408]{2,1,0} custom-call(broadcast.2), custom_call_target="Sharding", sharding={devices=[8,1,1,1024]<=[8192] last_tile_dim_replicate}, backend_config="unspecified_dims=[1,2]" custom-call.6 = bf16[8,384,1408]{2,1,0} custom-call(custom-call.3), custom_call_target="Sharding", custom_call_has_side_effect=true, sharding={unknown shard_as 1} %shard-barrier-to = bf16[8,384,1408]{2,1,0} custom-call(%custom-call.6), custom_call_target="ShardBarrierTo", custom_call_has_side_effect=true slice.7 = bf16[1,384,1408]{2,1,0} slice(shard-barrier-to), slice={[1:2], [0:384], [0:1408]} reshape.8 = bf16[384,1408]{1,0} reshape(slice.7) tuple.9 = (bf16[384,1408]{1,0}) tuple(reshape.8) get-tuple-element.10 = bf16[384,1408]{1,0} get-tuple-element(tuple.9), index=0, sharding={devices=[16,1,512]<=[8,16,64]T(1,0,2) last_tile_dim_replicate} ROOT tuple.13 = (bf16[384,1408]{1,0}, bf16[8,384,1408]{2,1,0}) tuple(get-tuple-element.10, custom-call.5) })"; TF_ASSERT_OK_AND_ASSIGN(auto module, ParseAndReturnVerifiedModule(hlo_string)); TF_ASSERT_OK_AND_ASSIGN( bool changed, ShardingPropagation( /*is_spmd=*/true, /*propagate_metadata=*/true, /*allow_spmd_sharding_propagation_to_output=*/{true}, /*allow_spmd_sharding_propagation_to_parameters=*/{false, false}) .Run(module.get())); EXPECT_TRUE(changed); XLA_VLOG_LINES(1, module->ToString()); auto* broadcast_4 = FindInstruction(module.get(), "broadcast.4"); ASSERT_NE(broadcast_4, nullptr); EXPECT_THAT( broadcast_4, op::Sharding("{devices=[8,1,16,64]<=[8192] last_tile_dim_replicate}")); auto* copy = FindInstruction(module.get(), "copy"); ASSERT_NE(copy, nullptr); EXPECT_THAT( copy, op::Sharding("{devices=[8,1,16,64]<=[8192] last_tile_dim_replicate}")); }
ShardingPropagationTest_ShardAsWithShardBarrier2
xla/service/sharding_propagation_test.cc
std::optional<HloSharding> ReturnImprovedSharding( HloSharding sharding, HloInstruction* instruction, bool may_combine_partial_sharding, bool allow_aggressive_resharding = false) { return hlo_sharding_util::ReturnImprovedShardingImpl( std::move(sharding), instruction->has_sharding() ? &instruction->sharding() : nullptr, instruction->shape(), may_combine_partial_sharding, allow_aggressive_resharding); } std::optional<HloSharding> ReturnImprovedSubSharding( HloSharding sharding, HloInstruction* instruction, const ShapeIndex& index, bool may_combine_partial_sharding, bool allow_aggressive_resharding = false) { if (instruction->has_sharding()) { const HloSharding to_improved = instruction->sharding().GetSubSharding(instruction->shape(), index); return hlo_sharding_util::ReturnImprovedShardingImpl( std::move(sharding), &to_improved, ShapeUtil::GetSubshape(instruction->shape(), index), may_combine_partial_sharding, allow_aggressive_resharding); } else { return hlo_sharding_util::ReturnImprovedShardingImpl( std::move(sharding), nullptr, ShapeUtil::GetSubshape(instruction->shape(), index), may_combine_partial_sharding, allow_aggressive_resharding); } } bool MaybeImproveInstructionSharding(HloSharding sharding, HloInstruction* instruction, bool may_combine_partial_sharding, bool allow_aggressive_resharding = false) { if (auto new_sharding = ReturnImprovedSharding( std::move(sharding), instruction, may_combine_partial_sharding, allow_aggressive_resharding)) { instruction->set_sharding(std::move(*new_sharding)); return true; } return false; } bool MaybeImproveInstructionSubSharding( HloSharding sharding, HloInstruction* instruction, const ShapeIndex& index, bool may_combine_partial_sharding, bool allow_aggressive_resharding = false) { if (instruction->shape().IsTuple()) { if (auto new_sub_sharding = ReturnImprovedSubSharding( std::move(sharding), instruction, index, may_combine_partial_sharding, allow_aggressive_resharding)) { HloSharding new_sharding = instruction->has_sharding() ? instruction->sharding() : HloSharding::Single(instruction->shape(), HloSharding::Replicate()); ShapeTree<HloSharding> sharding_shape_tree = new_sharding.GetAsShapeTree(instruction->shape()); *sharding_shape_tree.mutable_element(index) = new_sub_sharding.value(); instruction->set_sharding(HloSharding::Tuple(sharding_shape_tree)); return true; } else { return false; } } CHECK(index.size() == 1 && index[0] == 0); return MaybeImproveInstructionSharding(std::move(sharding), instruction, may_combine_partial_sharding, allow_aggressive_resharding); } bool IsConvolutionKernelSmall(const HloInstruction* instruction) { CHECK_EQ(instruction->opcode(), HloOpcode::kConvolution); const HloInstruction* rhs = instruction->operand(1); const auto& dnums = instruction->convolution_dimension_numbers(); int64_t kernel_dim_prod = 1; int64_t output_dim_prod = 1; for (int64_t i = 0; i < dnums.input_spatial_dimensions().size(); ++i) { int64_t kernel_dim = rhs->shape().dimensions(dnums.kernel_spatial_dimensions(i)); kernel_dim_prod *= kernel_dim; int64_t output_dim = instruction->shape().dimensions(dnums.output_spatial_dimensions(i)); output_dim_prod *= output_dim; if (kernel_dim >= output_dim && (i < 2 || kernel_dim > 3 || kernel_dim_prod >= output_dim_prod)) { return false; } } return true; } bool IsPassthroughCustomOps(const HloInstruction* hlo) { if (hlo->IsCustomCall({"Sharding", "X64Combine", "LayoutConstraint"})) { return true; } if (hlo->operand_count() != 1 || !hlo->shape().IsArray() || !hlo->operand(0)->shape().IsArray() || hlo->operand(0)->shape().rank() != hlo->shape().rank()) { return false; } return hlo->IsCustomCall( {"ResizeNearest", "ResizeBilinear", "ResizeNearestGrad", "ResizeBilinearGrad", "Cholesky", host_memory_offload_annotations::kMoveToDeviceCustomCallTarget, host_memory_offload_annotations::kMoveToHostCustomCallTarget}); } const HloInstruction* PickRepresentativeOperand( const HloInstruction* instruction) { switch (instruction->opcode()) { case HloOpcode::kMap: case HloOpcode::kPad: case HloOpcode::kPower: case HloOpcode::kOptimizationBarrier: case HloOpcode::kReverse: case HloOpcode::kSlice: case HloOpcode::kShiftLeft: case HloOpcode::kShiftRightArithmetic: case HloOpcode::kShiftRightLogical: // For these opcodes the output sharding has to be determined by the // sharding of the first operand but we can only determine sharding based // on it if it already has a sharding. if (instruction->operand(0)->has_sharding()) { return instruction->operand(0); } return nullptr; case HloOpcode::kAbs: case HloOpcode::kAdd: case HloOpcode::kAnd: case HloOpcode::kAtan2: case HloOpcode::kBitcastConvert: case HloOpcode::kCeil: case HloOpcode::kClamp: case HloOpcode::kClz: case HloOpcode::kCompare: case HloOpcode::kComplex: case HloOpcode::kConcatenate: case HloOpcode::kConvert: case HloOpcode::kCopy: case HloOpcode::kCos: case HloOpcode::kAllGather: case HloOpcode::kAllReduce: case HloOpcode::kReduceScatter: case HloOpcode::kAllToAll: case HloOpcode::kCollectiveBroadcast: case HloOpcode::kCollectivePermute: case HloOpcode::kDivide: case HloOpcode::kErf: case HloOpcode::kExp: case HloOpcode::kExpm1: case HloOpcode::kFloor: case HloOpcode::kImag: case HloOpcode::kIsFinite: case HloOpcode::kLog: case HloOpcode::kLog1p: case HloOpcode::kLogistic: case HloOpcode::kMaximum: case HloOpcode::kMinimum: case HloOpcode::kMultiply: case HloOpcode::kNegate: case HloOpcode::kNot: case HloOpcode::kOr: case HloOpcode::kPopulationCount: case HloOpcode::kReal: case HloOpcode::kReducePrecision: case HloOpcode::kRemainder: case HloOpcode::kRoundNearestAfz: case HloOpcode::kRoundNearestEven: case HloOpcode::kRsqrt: case HloOpcode::kSelect: case HloOpcode::kSign: case HloOpcode::kSin: case HloOpcode::kTopK: case HloOpcode::kSort: case HloOpcode::kSqrt: case HloOpcode::kCbrt: case HloOpcode::kSubtract: case HloOpcode::kStochasticConvert: case HloOpcode::kTan: case HloOpcode::kTanh: case HloOpcode::kWhile: case HloOpcode::kXor: { // For these opcodes the output sharding can be determined by any operand // so we find the operand with the most specific sharding. const HloInstruction* best_operand = nullptr; for (const HloInstruction* operand : instruction->operands()) { if (operand->has_sharding() && (best_operand == nullptr || hlo_sharding_util::IsShardingMoreSpecific( operand->sharding(), best_operand->sharding()))) { best_operand = operand; } } return best_operand; } case HloOpcode::kCustomCall: { if (IsPassthroughCustomOps(instruction)) { return instruction->operand(0); } return nullptr; } // There is no suitable operand for the rest of the opcodes. case HloOpcode::kAddDependency: case HloOpcode::kAfterAll: case HloOpcode::kAsyncStart: case HloOpcode::kAsyncUpdate: case HloOpcode::kAsyncDone: case HloOpcode::kAllGatherStart: case HloOpcode::kAllGatherDone: case HloOpcode::kAllReduceStart: case HloOpcode::kAllReduceDone: case HloOpcode::kBatchNormGrad: case HloOpcode::kBatchNormInference: case HloOpcode::kBatchNormTraining: case HloOpcode::kBitcast: case HloOpcode::kBroadcast: case HloOpcode::kCall: case HloOpcode::kCholesky: case HloOpcode::kCollectivePermuteDone: case HloOpcode::kCollectivePermuteStart: case HloOpcode::kConditional: case HloOpcode::kConstant: case HloOpcode::kConvolution: case HloOpcode::kCopyDone: case HloOpcode::kCopyStart: case HloOpcode::kDomain: case HloOpcode::kDot: case HloOpcode::kDynamicSlice: case HloOpcode::kDynamicUpdateSlice: case HloOpcode::kDynamicReshape: case HloOpcode::kFft: case HloOpcode::kFusion: case HloOpcode::kGather: case HloOpcode::kGetTupleElement: case HloOpcode::kInfeed: case HloOpcode::kIota: case HloOpcode::kOutfeed: case HloOpcode::kParameter: case HloOpcode::kPartitionId: case HloOpcode::kRecv: case HloOpcode::kRecvDone: case HloOpcode::kReduce: case HloOpcode::kReduceWindow: case HloOpcode::kReplicaId: case HloOpcode::kReshape: case HloOpcode::kRng: case HloOpcode::kRngGetAndUpdateState: case HloOpcode::kRngBitGenerator: case HloOpcode::kScatter: case HloOpcode::kSelectAndScatter: case HloOpcode::kSend: case HloOpcode::kSendDone: case HloOpcode::kTranspose: case HloOpcode::kTriangularSolve: case HloOpcode::kTuple: case HloOpcode::kGetDimensionSize: case HloOpcode::kSetDimensionSize: return nullptr; } } bool SupportSpatialPartitioning( const HloInstruction* instruction, const ShardingPropagation::ComputationMap& computation_map, bool is_spmd, bool allow_spmd_sharding_propagation_to_output, bool allow_spmd_sharding_propagation_to_parameters, const CustomCallShardingHelper* sharding_helper) { const bool is_entry_root = instruction->parent() ->parent() ->entry_computation() ->root_instruction() == instruction; if (instruction->parent()->root_instruction() == instruction && computation_map.find(instruction->parent()) == computation_map.end() && !(is_entry_root && allow_spmd_sharding_propagation_to_output)) { // We don't support sharding the root instruction of a computation yet, // unless the computation is a while body. return false; } if (instruction->IsElementwise() && (instruction->opcode() != HloOpcode::kRng || is_spmd)) { return true; } switch (instruction->opcode()) { case HloOpcode::kBroadcast: case HloOpcode::kConcatenate: case HloOpcode::kConditional: case HloOpcode::kConstant: case HloOpcode::kConvolution: case HloOpcode::kOptimizationBarrier: case HloOpcode::kDot: case HloOpcode::kDynamicSlice: case HloOpcode::kDynamicUpdateSlice: case HloOpcode::kGather: case HloOpcode::kGetTupleElement: case HloOpcode::kInfeed: case HloOpcode::kIota: case HloOpcode::kPad: case HloOpcode::kReduceWindow: case HloOpcode::kReshape: case HloOpcode::kScatter: case HloOpcode::kSelectAndScatter: case HloOpcode::kSlice: case HloOpcode::kSort: case HloOpcode::kTranspose: case HloOpcode::kTuple: case HloOpcode::kWhile: case HloOpcode::kReduce: case HloOpcode::kRngBitGenerator: case HloOpcode::kAllReduce: case HloOpcode::kReduceScatter: return true; case HloOpcode::kParameter: return allow_spmd_sharding_propagation_to_parameters || computation_map.find(instruction->parent()) != computation_map.end(); case HloOpcode::kReverse: return is_spmd; case HloOpcode::kCustomCall: if (!is_spmd) { return false; } if (auto* partitioner = GetCustomCallPartitioner(instruction->custom_call_target())) { return partitioner->IsCustomCallShardable(instruction); } return (IsPassthroughCustomOps(instruction) || sharding_helper->IsCustomCallShardable(instruction)); default: return false; } } std::optional<HloSharding> LookaheadUserSharding(HloInstruction* instr, bool is_spmd, const CallGraph& call_graph) { if (instr->user_count() != 1) { return std::nullopt; } HloInstruction* current_user = instr->users()[0]; std::optional<HloSharding> sharding; std::vector<HloInstruction*> users_chain = {instr, current_user}; // Collect single user instructions along the way. while (!current_user->has_sharding()) { // Only consider single user chains. if (current_user->users().size() != 1) { users_chain.clear(); break; } current_user = current_user->users()[0]; users_chain.push_back(current_user); } // Early exit for unsupported cases. if (users_chain.empty()) { return std::nullopt; } for (int i = users_chain.size() - 1; i >= 1; --i) { HloInstruction* user = users_chain[i]; HloInstruction* current = users_chain[i - 1]; CHECK(user->has_sharding()); sharding = ShardingPropagation::GetShardingFromUser( *current, *user, INT64_MAX, is_spmd, call_graph, /*sharding_helper=*/nullptr); // We need to set the sharding to the instruction, because // GetShardingFromUser() interface uses sharding from the instruction // itself. It will be cleared out later. if (sharding.has_value() && i != 1) { current->set_sharding(*sharding); continue; } break; } // Clear the sharding of the middle instructions we set the sharding of // because they were unsharded. for (int i = 1; i < users_chain.size() - 1; ++i) { users_chain[i]->clear_sharding(); } return sharding; } bool InferGatherParallelShardingFromOperands( HloInstruction* instruction, const hlo_sharding_util::GatherScatterParallelDims& parallel_dims, bool may_combine_partial_sharding) { CHECK(DynCast<HloGatherInstruction>(instruction)); bool changed = false; auto aligned_operand_parallel_dims = hlo_sharding_util::IndexAlignedOperandParallelDims(parallel_dims); auto output_parallel_dims = hlo_sharding_util::GetGatherParallelOutputDims( *instruction, parallel_dims); // Infer output sharding from scatter operand sharding. if (hlo_sharding_util::IsSpatiallyPartitioned(instruction->operand(0))) { changed |= MaybeImproveInstructionSharding( hlo_sharding_util:: InferGatherScatterParallelShardingFromOperandSharding( instruction->operand(0)->sharding(), instruction->operand(0)->shape(), instruction->shape(), absl::MakeConstSpan(aligned_operand_parallel_dims), absl::MakeConstSpan(output_parallel_dims)), instruction, may_combine_partial_sharding); } // Infer output sharding from scatter indices sharding. if (hlo_sharding_util::IsSpatiallyPartitioned(instruction->operand(1))) { changed |= MaybeImproveInstructionSharding( hlo_sharding_util:: InferGatherScatterParallelShardingFromOperandSharding( instruction->operand(1)->sharding(), instruction->operand(1)->shape(), instruction->shape(), absl::MakeConstSpan(parallel_dims.indices_parallel_dims), absl::MakeConstSpan(output_parallel_dims)), instruction, may_combine_partial_sharding); } return changed; } bool InferScatterParallelShardingFromOperands( HloInstruction* instruction, const hlo_sharding_util::GatherScatterParallelDims& parallel_dims, bool may_combine_partial_sharding) { HloScatterInstruction* scatter = DynCast<HloScatterInstruction>(instruction); CHECK(scatter); const int64_t operand_count = scatter->scatter_operand_count(); auto scatter_operands = scatter->scatter_operands(); auto scatter_indices = scatter->scatter_indices(); auto scatter_updates = scatter->scatter_updates(); bool changed = false; auto aligned_operand_parallel_dims = hlo_sharding_util::IndexAlignedOperandParallelDims(parallel_dims); auto update_parallel_dims = hlo_sharding_util::GetScatterParallelUpdateDims( *instruction, parallel_dims); auto output_parallel_dims = aligned_operand_parallel_dims; // Infer output sharding from scatter operand sharding. Shape shape = operand_count == 1 ? instruction->shape() : ShapeUtil::GetSubshape(instruction->shape(), {0}); for (int64_t i = 0; i != operand_count; ++i) { if (hlo_sharding_util::IsSpatiallyPartitioned(scatter_operands[i])) { changed |= MaybeImproveInstructionSubSharding( hlo_sharding_util:: InferGatherScatterParallelShardingFromOperandSharding( scatter_operands[i]->sharding(), scatter_operands[i]->shape(), shape, absl::MakeConstSpan(aligned_operand_parallel_dims), absl::MakeConstSpan(output_parallel_dims)), instruction, {i}, may_combine_partial_sharding); } } // Infer output sharding from scatter indices sharding. if (hlo_sharding_util::IsSpatiallyPartitioned(scatter_indices)) { auto parallel_sharding_from_indices = hlo_sharding_util:: InferGatherScatterParallelShardingFromOperandSharding( scatter_indices->sharding(), scatter_indices->shape(), shape, absl::MakeConstSpan(parallel_dims.indices_parallel_dims), absl::MakeConstSpan(output_parallel_dims)); for (int64_t i = 0; i != operand_count; ++i) { changed |= MaybeImproveInstructionSubSharding( parallel_sharding_from_indices, instruction, {i}, may_combine_partial_sharding); } } // Infer output sharding from scatter update sharding. for (int64_t i = 0; i != operand_count; ++i) { if (hlo_sharding_util::IsSpatiallyPartitioned(scatter_updates[i])) { changed |= MaybeImproveInstructionSubSharding( hlo_sharding_util:: InferGatherScatterParallelShardingFromOperandSharding( scatter_updates[i]->sharding(), scatter_updates[i]->shape(), shape, absl::MakeConstSpan(update_parallel_dims), absl::MakeConstSpan(output_parallel_dims)), instruction, {i}, may_combine_partial_sharding); } } return changed; } bool CanPropagateThroughAtAggressiveLevel(const HloInstruction& inst, int64_t aggressiveness) { // At minimum aggressiveness, only allow pass-through ops. if (aggressiveness < 1 && !(inst.IsElementwise() || inst.IsCustomCall("Sharding")) && inst.opcode() != HloOpcode::kTranspose && inst.opcode() != HloOpcode::kReshape && inst.opcode() != HloOpcode::kTuple && inst.opcode() != HloOpcode::kGetTupleElement && inst.opcode() != HloOpcode::kWhile && inst.opcode() != HloOpcode::kDynamicSlice && inst.opcode() != HloOpcode::kDynamicUpdateSlice && inst.opcode() != HloOpcode::kOptimizationBarrier && inst.opcode() != HloOpcode::kConcatenate && inst.opcode() != HloOpcode::kCall && inst.opcode() != HloOpcode::kCopy) { return false; } // Broadcast propagation should have at least aggressiveness 2. if (aggressiveness < 2 && inst.opcode() == HloOpcode::kBroadcast) { return false; } return true; } bool SameShardingMetadata(const HloSharding& a, const HloSharding& b) { DCHECK_EQ(a, b); auto same_metadata = [](absl::Span<const OpMetadata> a, absl::Span<const OpMetadata> b) { if (a.size() != b.size()) return false; for (int i = 0, e = a.size(); i < e; ++i) { if (!protobuf_util::ProtobufEquals(a[i], b[i])) { return false; } } return true; }; if (a.IsTuple()) { for (int i = 0, e = a.tuple_elements().size(); i < e; ++i) { if (!same_metadata(a.tuple_elements()[i].metadata(), b.tuple_elements()[i].metadata())) { return false; } } return true; } else { return same_metadata(a.metadata(), b.metadata()); } } auto same_metadata = [](absl::Span<const OpMetadata> a, absl::Span<const OpMetadata> b) { if (a.size() != b.size()) return false; for (int i = 0, e = a.size(); i < e; ++i) { if (!protobuf_util::ProtobufEquals(a[i], b[i])) { return false; } } return true; }; bool AssignShardingMetadata( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { bool changed = false; for (HloComputation* computation : module->computations(execution_threads)) { for (HloInstruction* instruction : computation->instructions()) { const auto& metadata = instruction->metadata(); if (!instruction->has_sharding() || metadata.ByteSizeLong() == 0) { continue; } HloSharding sharding_with_metadata = instruction->sharding().WithMetadata({metadata}, /*overwrite=*/false); if (!SameShardingMetadata(instruction->sharding(), sharding_with_metadata)) { instruction->set_sharding(std::move(sharding_with_metadata)); changed = true; } } } return changed; } bool RemoveShardingMetadata( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { bool changed = false; for (HloComputation* computation : module->computations(execution_threads)) { for (HloInstruction* instruction : computation->instructions()) { if (!instruction->has_sharding()) { continue; } HloSharding sharding_no_metadata = instruction->sharding().WithoutMetadata(); if (!SameShardingMetadata(instruction->sharding(), sharding_no_metadata)) { instruction->set_sharding(std::move(sharding_no_metadata)); changed = true; } } } return changed; } absl::Status CheckAndUpdateDeviceAssignmentsInWhileBody( HloInstruction* while_instruction) { auto bad_status = [](HloInstruction* instruction, int64_t device, HloInstruction* channel_instruction, int64_t correct_device) { return FailedPrecondition( "Instruction: %s is on device: %d, which conflicts with device: %d " "of channel instruction: %s", instruction->name(), device, correct_device, channel_instruction->name()); }; CHECK_EQ(while_instruction->opcode(), HloOpcode::kWhile); HloComputation* while_body = while_instruction->while_body(); // Maps a device number to an instruction in the while_body with that // device assignment. std::map<int64_t, HloInstruction*> devices_to_instructions; std::optional<int64_t> unique_device = std::nullopt; HloInstruction* channel_instruction = nullptr; for (HloInstruction* instruction : while_body->instructions()) { if (instruction->sharding_unique_device()) { auto opcode = instruction->opcode(); int64_t device = *instruction->sharding_unique_device(); if (unique_device.has_value()) { if (*unique_device != device) { return bad_status(instruction, device, channel_instruction, *unique_device); } } else if (((opcode == HloOpcode::kSend || opcode == HloOpcode::kRecv) && !Cast<HloSendRecvInstruction>(instruction) ->is_host_transfer()) // Cross-replica AllReduces don't have a channel_id, and we // don't enforce any invariant about their device assignment. || ((opcode == HloOpcode::kAllReduce || opcode == HloOpcode::kReduceScatter) && instruction->channel_id())) { channel_instruction = instruction; unique_device = device; if (!devices_to_instructions.empty()) { for (auto it = devices_to_instructions.begin(); it != devices_to_instructions.end(); ++it) { if (*unique_device != it->first) { return bad_status(it->second, it->first, channel_instruction, *unique_device); } } } } else { devices_to_instructions[device] = instruction; } } } if (unique_device.has_value()) { auto while_device = while_instruction->sharding_unique_device(); if (while_device.has_value() && *unique_device != *while_device) { return bad_status(while_instruction, *while_device, channel_instruction, *unique_device); } auto body_root = while_body->root_instruction(); auto root_device = body_root->sharding_unique_device(); if (!root_device.has_value()) { body_root->set_device_sharding(*unique_device); } else if (*unique_device != *root_device) { return bad_status(body_root, *root_device, channel_instruction, *unique_device); } } return absl::OkStatus(); } auto bad_status = [](HloInstruction* instruction, int64_t device, HloInstruction* channel_instruction, int64_t correct_device) { return FailedPrecondition( "Instruction: %s is on device: %d, which conflicts with device: %d " "of channel instruction: %s", instruction->name(), device, correct_device, channel_instruction->name()); }; bool RefineManualAutoShardingFromAuto( const HloSharding& to_merge, absl::Span<const int64_t> unspecified_dims, HloSharding* auto_sharding, HloSharding* manual_sharding) { if (!manual_sharding->IsManualSubgroup() || auto_sharding->IsManualSubgroup() || !manual_sharding->HasPartialReplication() || manual_sharding->subgroup_types().size() != 2) { // We do not support nested subgroup manual. man_conversion_op must have // replication in order to be merged. return false; } HloSharding partial_rep = hlo_sharding_util::PartiallyReplicateTiledShardingOnAllDimsExcept( to_merge, unspecified_dims); if (partial_rep.IsTileMaximal()) { return false; } // Merge with the non-manual partial annotation. if (!hlo_sharding_util::MergeShardingIfCompatible( partial_rep, auto_sharding->NumTiles() + 1, auto_sharding)) { return false; } // Merge with the manual partial annotation. const int64_t data_rank = partial_rep.TiledDataRank(); // We are also merging the non-manual sharding into the manual sharding. To // leverage existing merging implementation, we treat the manual dim as a // data dim, and add it right before the replication dim. std::vector<int64_t> partial_manual_shape( partial_rep.tile_assignment().dimensions().begin(), partial_rep.tile_assignment().dimensions().end()); partial_manual_shape.insert(partial_manual_shape.begin() + data_rank, 1); auto partial_tiling_for_manual = partial_rep.tile_assignment().Reshape(partial_manual_shape); HloSharding partial_rep_for_manual = HloSharding::PartialTile( partial_tiling_for_manual, partial_rep.metadata()); auto man_tiling = manual_sharding->tile_assignment(); if (manual_sharding->subgroup_types().back() != OpSharding::REPLICATED) { // Move the manual dim before replication dim. std::vector<int> transposed_dims(man_tiling.num_dimensions()); absl::c_iota(transposed_dims, 0); std::swap(transposed_dims.back(), transposed_dims[data_rank]); man_tiling = man_tiling.Transpose(transposed_dims); } HloSharding tmp_sharding_for_merging = HloSharding::PartialTile( std::move(man_tiling), manual_sharding->metadata()); if (!hlo_sharding_util::MergeShardingIfCompatible( partial_rep_for_manual, tmp_sharding_for_merging.NumTiles() + 1, &tmp_sharding_for_merging)) { return false; } std::vector<OpSharding::Type> subgroup_types; subgroup_types.push_back(OpSharding::MANUAL); if (tmp_sharding_for_merging.HasPartialReplication()) { subgroup_types.push_back(OpSharding::REPLICATED); } *manual_sharding = HloSharding::Subgroup( tmp_sharding_for_merging.tile_assignment(), subgroup_types, tmp_sharding_for_merging.metadata()); return true; } bool RefineManualAutoShardingFromManual( const HloSharding& to_merge, absl::Span<const int64_t> unspecified_dims, HloSharding* auto_sharding, HloSharding* manual_sharding) { if (!to_merge.IsManualSubgroup() || !manual_sharding->IsManualSubgroup() || !manual_sharding->HasPartialReplication() || auto_sharding->IsManualSubgroup() || manual_sharding->subgroup_types().size() != 2) { return false; } HloSharding partial_rep = hlo_sharding_util::PartiallyReplicateTiledShardingOnAllDimsExcept( to_merge, unspecified_dims); if (partial_rep.IsTileMaximal()) { return false; } if (!hlo_sharding_util::MergeShardingIfCompatible( partial_rep, manual_sharding->NumTiles() + 1, manual_sharding)) { return false; } HloSharding partial_rep_for_auto = HloSharding::Subgroup( partial_rep.tile_assignment(), std::vector<OpSharding::Type>(partial_rep.subgroup_types().size(), OpSharding::REPLICATED), partial_rep.metadata()); if (!hlo_sharding_util::MergeShardingIfCompatible( partial_rep_for_auto, auto_sharding->NumTiles() + 1, auto_sharding)) { return false; } return true; } bool InferUnspecifiedDimsFromOperand(HloInstruction* annotate_op, absl::Span<const int64_t> unspecified_dims, HloInstruction** man_conversion_op_after) { // ProcessShardingInstruction will either keep the "Sharding" custom call as // is or replace it with a copy. CHECK(annotate_op->IsCustomCall("Sharding") || annotate_op->opcode() == HloOpcode::kCopy); if (!hlo_sharding_util::IsSpatiallyPartitioned(annotate_op->operand(0))) { return false; } const HloSharding& operand_sharding = annotate_op->operand(0)->sharding(); if (!operand_sharding.IsTiled()) { return false; } HloInstruction* man_conversion_op = nullptr; if (annotate_op->user_count() == 1) { HloInstruction* user = annotate_op->users()[0]; if (user->IsCustomCall("SPMDFullToShardShape") || user->IsCustomCall("SPMDShardToFullShape")) { std::vector<int64_t> user_unspec_dims; if (!sharding_op_util::ParseAttributes( Cast<HloCustomCallInstruction>(user)->opaque(), &user_unspec_dims) .ok()) { return false; } absl::c_sort(user_unspec_dims); if (unspecified_dims != user_unspec_dims) { // The manual/auto conversion op must have the same set of unspecified // dims. return false; } man_conversion_op = user; } } *man_conversion_op_after = man_conversion_op; if (man_conversion_op == nullptr) { HloSharding partial_replicated = hlo_sharding_util::PartiallyReplicateTiledShardingOnAllDimsExcept( operand_sharding, unspecified_dims); HloSharding sharding = annotate_op->sharding(); if (!hlo_sharding_util::MergeShardingIfCompatible( partial_replicated, sharding.NumTiles() + 1, &sharding)) { return false; } annotate_op->set_sharding(sharding); return true; } if (man_conversion_op->IsCustomCall("SPMDFullToShardShape")) { HloSharding auto_sharding = annotate_op->sharding(); HloSharding manual_sharding = man_conversion_op->sharding(); if (!RefineManualAutoShardingFromAuto(operand_sharding, unspecified_dims, &auto_sharding, &manual_sharding)) { return false; } annotate_op->set_sharding(auto_sharding); man_conversion_op->set_sharding(manual_sharding); return true; } CHECK(man_conversion_op->IsCustomCall("SPMDShardToFullShape")); HloSharding manual_sharding = annotate_op->sharding(); HloSharding auto_sharding = man_conversion_op->sharding(); if (!RefineManualAutoShardingFromManual(operand_sharding, unspecified_dims, &auto_sharding, &manual_sharding)) { return false; } annotate_op->set_sharding(manual_sharding); man_conversion_op->set_sharding(auto_sharding); return true; } bool InferUnspecifiedDimsFromOneUser(HloInstruction* annotate_op, const HloInstruction* user, int64_t aggressiveness, bool is_spmd, absl::Span<const int64_t> unspecified_dims, HloInstruction* man_conversion_op, const CallGraph& call_graph) { CHECK(annotate_op->IsCustomCall("Sharding") || annotate_op->opcode() == HloOpcode::kCopy); if (!user->has_sharding() || !user->sharding().IsTiled()) { return false; } std::optional<HloSharding> user_sharding = ShardingPropagation::GetShardingFromUser( man_conversion_op == nullptr ? *annotate_op : *man_conversion_op, *user, aggressiveness, is_spmd, call_graph, /*sharding_helper=*/nullptr); if (!user_sharding.has_value() || user_sharding->IsTileMaximal()) { return false; } if (man_conversion_op == nullptr) { HloSharding partial_replicated = hlo_sharding_util::PartiallyReplicateTiledShardingOnAllDimsExcept( *user_sharding, unspecified_dims); HloSharding sharding = annotate_op->sharding(); if (!hlo_sharding_util::MergeShardingIfCompatible( partial_replicated, sharding.NumTiles() + 1, &sharding)) { return false; } annotate_op->set_sharding(sharding); return true; } if (man_conversion_op->IsCustomCall("SPMDFullToShardShape")) { HloSharding auto_sharding = annotate_op->sharding(); HloSharding manual_sharding = man_conversion_op->sharding(); if (!RefineManualAutoShardingFromManual(*user_sharding, unspecified_dims, &auto_sharding, &manual_sharding)) { return false; } annotate_op->set_sharding(auto_sharding); man_conversion_op->set_sharding(manual_sharding); return true; } CHECK(man_conversion_op->IsCustomCall("SPMDShardToFullShape")); HloSharding manual_sharding = annotate_op->sharding(); HloSharding auto_sharding = man_conversion_op->sharding(); if (!RefineManualAutoShardingFromAuto(*user_sharding, unspecified_dims, &auto_sharding, &manual_sharding)) { return false; } annotate_op->set_sharding(manual_sharding); man_conversion_op->set_sharding(auto_sharding); return true; } bool InferUnspecifiedDimsFromUsers(HloInstruction* annotate_op, absl::Span<const int64_t> unspecified_dims, int64_t aggressiveness, bool is_spmd, HloInstruction** man_conversion_op_after, const CallGraph& call_graph) { HloInstruction* man_conversion_op = nullptr; if (annotate_op->user_count() == 1) { HloInstruction* user = annotate_op->users()[0]; if (user->IsCustomCall("SPMDFullToShardShape") || user->IsCustomCall("SPMDShardToFullShape")) { std::vector<int64_t> user_unspec_dims; absl::c_sort(user_unspec_dims); if (!sharding_op_util::ParseAttributes( Cast<HloCustomCallInstruction>(user)->opaque(), &user_unspec_dims) .ok() || unspecified_dims != user_unspec_dims) { // The manual/auto conversion op must have the same set of unspecified // dims. return false; } man_conversion_op = user; } } *man_conversion_op_after = man_conversion_op; HloInstruction* op_for_users = man_conversion_op == nullptr ? annotate_op : man_conversion_op; bool changed = false; for (HloInstruction* user : op_for_users->users()) { changed |= InferUnspecifiedDimsFromOneUser( annotate_op, user, aggressiveness, is_spmd, unspecified_dims, man_conversion_op, call_graph); } return changed; } bool InferUnspecifiedDimsFromShardGroup( HloInstruction* annotate_op, absl::Span<const int64_t> unspecified_dims, const absl::flat_hash_set<HloInstruction*>& shard_group) { // ProcessShardingInstruction will either keep the "Sharding" custom call as // is or replace it with a copy. CHECK(annotate_op->IsCustomCall("Sharding") || annotate_op->opcode() == HloOpcode::kCopy); // Do not propagate sharding to ShardBarrierTo custom-call. if (annotate_op->IsCustomCall(spmd::kShardBarrierTo)) { return false; } bool changed = false; for (const HloInstruction* member : shard_group) { if (member == annotate_op) { continue; } // Do not propagate sharding from ShardBarrierFrom custom-call. if (member->IsCustomCall(spmd::kShardBarrierFrom)) { continue; } if (!hlo_sharding_util::IsSpatiallyPartitioned(member)) { continue; } const HloSharding& member_sharding = member->sharding(); if (!member_sharding.IsTiled()) { continue; } HloSharding partial_replicated = hlo_sharding_util::PartiallyReplicateTiledShardingOnAllDimsExcept( member_sharding, unspecified_dims); HloSharding sharding = annotate_op->sharding(); if (!hlo_sharding_util::MergeShardingIfCompatible( partial_replicated, sharding.NumTiles() + 1, &sharding)) { continue; } annotate_op->set_sharding(sharding); changed |= true; } return changed; } bool IsCSEPreventionTarget(const HloInstruction* instruction) { // Scalar broadcasts are the most common CSE target that causes cross-layer // propagation on unrelated subgraphs. return instruction->opcode() == HloOpcode::kBroadcast && instruction->operand(0)->shape().rank() == 0; } HloSharding SetCSEPreventionSharding(const HloSharding& sharding) { OpMetadata metadata; metadata.set_op_name("_sharding_propagation_cse_prevention"); return sharding.WithMetadata({metadata}, /*overwrite=*/true); } bool IsCSEPreventionSharding(const HloSharding& sharding) { if (sharding.metadata().size() != 1) { return false; } return sharding.metadata()[0].op_name() == "_sharding_propagation_cse_prevention"; } bool InferDotShardingFromOperands( HloInstruction* instruction, const CallGraph& call_graph, const dot_as_convolution_util::DotConvolutionDimsInfo& dnums, bool may_combine_partial_sharding, bool is_spmd) { auto from_operand = [&](int64_t operand_index) { auto operand = instruction->operand(operand_index); const HloSharding& operand_sharding = operand->sharding(); if (operand_sharding.IsTileMaximal()) { return operand_sharding; } std::vector<int64_t> contracting_dims; contracting_dims.reserve(dnums.contracting_dims.size()); for (const auto& dim : dnums.contracting_dims) { contracting_dims.push_back(operand_index == 0 ? dim.lhs : dim.rhs); } // It's possible that some size-1 spatial dims of convolutions are parsed as // non-contracting dims. We might have tiled dimensions on them. for (const auto& dim : operand_index == 0 ? dnums.rhs_non_contracting_dims : dnums.lhs_non_contracting_dims) { int64_t d = operand_index == 0 ? dim.lhs : dim.rhs; if (d >= 0) { contracting_dims.push_back(d); } } auto replicate_contracting_dims = hlo_sharding_util::PartiallyReplicateTiledShardingOnDims( operand_sharding, contracting_dims); std::vector<int64_t> out_dims_to_op_perm(instruction->shape().rank(), -1); std::vector<int64_t> op_dims_to_output_perm(operand->shape().rank(), -1); for (const auto& dim : dnums.batch_dims) { out_dims_to_op_perm[dim.output] = operand_index == 0 ? dim.lhs : dim.rhs; op_dims_to_output_perm[operand_index == 0 ? dim.lhs : dim.rhs] = dim.output; } for (const auto& dim : operand_index == 0 ? dnums.lhs_non_contracting_dims : dnums.rhs_non_contracting_dims) { out_dims_to_op_perm[dim.output] = operand_index == 0 ? dim.lhs : dim.rhs; op_dims_to_output_perm[operand_index == 0 ? dim.lhs : dim.rhs] = dim.output; } return *hlo_sharding_util::TransposeShardingWithCollapsedDims( replicate_contracting_dims, op_dims_to_output_perm, out_dims_to_op_perm); }; std::optional<HloSharding> improved_operand_0; std::optional<HloSharding> improved_operand_1; if (hlo_sharding_util::IsSpatiallyPartitioned(instruction->operand(0))) { improved_operand_0 = ReturnImprovedSharding( from_operand(0), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/false); } if (hlo_sharding_util::IsSpatiallyPartitioned(instruction->operand(1))) { improved_operand_1 = ReturnImprovedSharding( from_operand(1), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/false); } // If not improved sharding found then do not set any sharding. if (!improved_operand_0.has_value() && !improved_operand_1.has_value()) { return false; } // Sharding found from operand 0 but not operand 1. Set sharding from operand // 0 if (improved_operand_0.has_value() && !improved_operand_1.has_value()) { instruction->set_sharding(*improved_operand_0); return true; } // Sharding found from operand 1 but not operand 0. Set sharding from operand // 1 if (!improved_operand_0.has_value() && improved_operand_1.has_value()) { instruction->set_sharding(*improved_operand_1); return true; } CHECK(improved_operand_0.has_value() && improved_operand_1.has_value()); std::optional<HloSharding> lookahead_sharding = LookaheadUserSharding(instruction, is_spmd, call_graph); std::array<HloSharding, 2> sharding_priority = {*improved_operand_0, *improved_operand_1}; bool priority_defined_with_lookahead = false; // Found sharding from lookahead. if (lookahead_sharding.has_value()) { const bool operand_0_is_lookahead_subtiling = hlo_sharding_util::IsSubTilingOrEqualSharding( instruction->shape(), *lookahead_sharding, *improved_operand_0); const bool operand_1_is_lookahead_subtiling = hlo_sharding_util::IsSubTilingOrEqualSharding( instruction->shape(), *lookahead_sharding, *improved_operand_1); // If the sharding from operand 0 is a subtiling of the user, but not the // one from operand 1 prioritize that sharding. if (operand_0_is_lookahead_subtiling && !operand_1_is_lookahead_subtiling) { priority_defined_with_lookahead = true; } // If the sharding from operand 1 is a subtiling of the user, but not the // one from operand 0 prioritize that sharding. if (!operand_0_is_lookahead_subtiling && operand_1_is_lookahead_subtiling) { instruction->set_sharding(*improved_operand_1); std::swap(sharding_priority[0], sharding_priority[1]); priority_defined_with_lookahead = true; } } // If lookahead didn't define a priority then use size. if (!priority_defined_with_lookahead && ShapeUtil::ByteSizeOf(instruction->operand(0)->shape()) < ShapeUtil::ByteSizeOf(instruction->operand(1)->shape())) { std::swap(sharding_priority[0], sharding_priority[1]); } // Set primary sharding to the instruction and then try to improve it with // the secondary sharding. instruction->set_sharding(sharding_priority[0]); MaybeImproveInstructionSharding(sharding_priority[1], instruction, may_combine_partial_sharding); return true; } auto from_operand = [&](int64_t operand_index) { auto operand = instruction->operand(operand_index); const HloSharding& operand_sharding = operand->sharding(); if (operand_sharding.IsTileMaximal()) { return operand_sharding; } std::vector<int64_t> contracting_dims; contracting_dims.reserve(dnums.contracting_dims.size()); for (const auto& dim : dnums.contracting_dims) { contracting_dims.push_back(operand_index == 0 ? dim.lhs : dim.rhs); } // It's possible that some size-1 spatial dims of convolutions are parsed as // non-contracting dims. We might have tiled dimensions on them. for (const auto& dim : operand_index == 0 ? dnums.rhs_non_contracting_dims : dnums.lhs_non_contracting_dims) { int64_t d = operand_index == 0 ? dim.lhs : dim.rhs; if (d >= 0) { contracting_dims.push_back(d); } } auto replicate_contracting_dims = hlo_sharding_util::PartiallyReplicateTiledShardingOnDims( operand_sharding, contracting_dims); std::vector<int64_t> out_dims_to_op_perm(instruction->shape().rank(), -1); std::vector<int64_t> op_dims_to_output_perm(operand->shape().rank(), -1); for (const auto& dim : dnums.batch_dims) { out_dims_to_op_perm[dim.output] = operand_index == 0 ? dim.lhs : dim.rhs; op_dims_to_output_perm[operand_index == 0 ? dim.lhs : dim.rhs] = dim.output; } for (const auto& dim : operand_index == 0 ? dnums.lhs_non_contracting_dims : dnums.rhs_non_contracting_dims) { out_dims_to_op_perm[dim.output] = operand_index == 0 ? dim.lhs : dim.rhs; op_dims_to_output_perm[operand_index == 0 ? dim.lhs : dim.rhs] = dim.output; } return *hlo_sharding_util::TransposeShardingWithCollapsedDims( replicate_contracting_dims, op_dims_to_output_perm, out_dims_to_op_perm); }; bool InferConvolutionShardingFromOperands(HloInstruction* instruction, const CallGraph& call_graph, int64_t aggressiveness, bool may_combine_partial_sharding, bool is_spmd) { auto get_partitions_for_dims = [&](const HloInstruction* inst, absl::Span< const dot_as_convolution_util::DotConvolutionDimsInfo::DimNums> dims, int lhs_or_rhs) { int64_t partitions = 1; if (!inst->has_sharding()) { return partitions; } const auto& sharding = inst->sharding(); if (sharding.IsTileMaximal()) { return partitions; } for (const auto& dim : dims) { if (lhs_or_rhs == 0) { partitions *= sharding.tile_assignment().dim(dim.lhs); } else { CHECK_EQ(lhs_or_rhs, 1); partitions *= sharding.tile_assignment().dim(dim.rhs); } } return partitions; }; auto dot_dims = dot_as_convolution_util::ParseConvolutionDimsInfo(instruction); const int64_t lhs_conv_spatial_partitions = get_partitions_for_dims( instruction->operand(0), dot_dims.conv_spatial_dims, 0); const int64_t rhs_conv_spatial_partitions = get_partitions_for_dims( instruction->operand(1), dot_dims.conv_spatial_dims, 1); if (dot_dims.conv_spatial_dims.empty() || (lhs_conv_spatial_partitions == 1 && rhs_conv_spatial_partitions == 1 && instruction->batch_group_count() == 1 && instruction->feature_group_count() == 1)) { return InferDotShardingFromOperands(instruction, call_graph, dot_dims, may_combine_partial_sharding, is_spmd); } const auto& dnums = instruction->convolution_dimension_numbers(); const HloInstruction* lhs = instruction->operand(0); auto get_tiled_sharding_based_on_lhs = [&] { CHECK(!lhs->sharding().IsTileMaximal()); std::vector<int64_t> output_to_lhs_indices(instruction->shape().rank()); output_to_lhs_indices[dnums.output_batch_dimension()] = dnums.input_batch_dimension(); output_to_lhs_indices[dnums.output_feature_dimension()] = dnums.input_feature_dimension(); for (int64_t i = 0; i < dnums.input_spatial_dimensions_size(); ++i) { output_to_lhs_indices[dnums.output_spatial_dimensions(i)] = dnums.input_spatial_dimensions(i); } return hlo_sharding_util::TransposeSharding(lhs->sharding(), output_to_lhs_indices); }; if (!hlo_sharding_util::IsSpatiallyPartitioned(lhs)) { return false; } if (lhs->sharding().IsTileMaximal()) { return MaybeImproveInstructionSharding(lhs->sharding(), instruction, may_combine_partial_sharding); } if (IsConvolutionKernelSmall(instruction)) { // If the kernel is small compared to the input then we can generate an // output what is sharded the same way as the input. const auto& tile_assignment = lhs->sharding().tile_assignment(); if (tile_assignment.dim(dnums.input_feature_dimension()) > 1) { return false; } return MaybeImproveInstructionSharding(get_tiled_sharding_based_on_lhs(), instruction, may_combine_partial_sharding); } // If the kernel is large (e.g., backward convolution) then we only support // replicated output. We intend to keep the sharding along the batch dimension // between lhs and output. return MaybeImproveInstructionSharding( hlo_sharding_util::PartiallyReplicateTiledShardingOnAllDimsExcept( lhs->sharding(), {dnums.input_batch_dimension()}), instruction, may_combine_partial_sharding); } [&](const HloInstruction* inst, absl::Span< const dot_as_convolution_util::DotConvolutionDimsInfo::DimNums> dims, int lhs_or_rhs) { int64_t partitions = 1; if (!inst->has_sharding()) { return partitions; } const auto& sharding = inst->sharding(); if (sharding.IsTileMaximal()) { return partitions; } for (const auto& dim : dims) { if (lhs_or_rhs == 0) { partitions *= sharding.tile_assignment().dim(dim.lhs); } else { CHECK_EQ(lhs_or_rhs, 1); partitions *= sharding.tile_assignment().dim(dim.rhs); } } return partitions; }; auto get_tiled_sharding_based_on_lhs = [&] { CHECK(!lhs->sharding().IsTileMaximal()); std::vector<int64_t> output_to_lhs_indices(instruction->shape().rank()); output_to_lhs_indices[dnums.output_batch_dimension()] = dnums.input_batch_dimension(); output_to_lhs_indices[dnums.output_feature_dimension()] = dnums.input_feature_dimension(); for (int64_t i = 0; i < dnums.input_spatial_dimensions_size(); ++i) { output_to_lhs_indices[dnums.output_spatial_dimensions(i)] = dnums.input_spatial_dimensions(i); } return hlo_sharding_util::TransposeSharding(lhs->sharding(), output_to_lhs_indices); }; std::optional<HloSharding> InferBroadcastOperandSharding( const HloInstruction& instruction, bool is_spmd) { if (instruction.sharding().IsReplicated() || instruction.sharding().IsManual()) { return instruction.sharding(); } std::vector<int64_t> dims_to_replicate; bool needs_replication = false; for (int64_t i = 0; i < instruction.shape().rank(); ++i) { if (absl::c_count(instruction.dimensions(), i) == 0) { dims_to_replicate.push_back(i); if (instruction.sharding().tile_assignment().dim(i) > 1) { needs_replication = true; } } } // If not SPMD, only support when none of the partitioned dimensions in // the broadcast output belong to new dimensions. if (!is_spmd && needs_replication) { return std::nullopt; } return hlo_sharding_util::RemoveShapeDimensions( hlo_sharding_util::PartiallyReplicateTiledShardingOnDims( instruction.sharding(), dims_to_replicate), dims_to_replicate); } bool InferReduceShardingFromOperand(HloInstruction* instruction, bool may_combine_partial_sharding, bool is_spmd) { auto get_maybe_tuple_sharding = [&](HloSharding sharding) { if (instruction->shape().IsArray()) { return sharding; } std::vector<HloSharding> tuple(instruction->shape().tuple_shapes_size(), std::move(sharding)); return HloSharding::Tuple(instruction->shape(), tuple); }; auto* reduce = Cast<HloReduceInstruction>(instruction); bool changed = false; for (HloInstruction* operand : reduce->inputs()) { if (!hlo_sharding_util::IsSpatiallyPartitioned(operand)) { continue; } if (operand->sharding().IsReplicated() || (!is_spmd && absl::c_any_of(instruction->dimensions(), [operand](int64_t dim) { return operand->sharding().tile_assignment().dim(dim) > 1; }))) { // We are reducing along one of the sharded dimensions. We only // support this in SPMD. changed |= MaybeImproveInstructionSharding( get_maybe_tuple_sharding( hlo_sharding_util::ReplicateAllDataDims(operand->sharding())), reduce, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); continue; } auto after_partial_replication = operand->sharding().IsReplicated() ? operand->sharding() : hlo_sharding_util::PartiallyReplicateTiledShardingOnDims( operand->sharding(), reduce->dimensions()); if (after_partial_replication.IsReplicated()) { changed |= MaybeImproveInstructionSharding( get_maybe_tuple_sharding(after_partial_replication), reduce, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); continue; } // Use the same sharding for all tuple elements, because they are part // of the same reduce instruction. HloSharding new_sharding = get_maybe_tuple_sharding(hlo_sharding_util::RemoveShapeDimensions( after_partial_replication, reduce->dimensions())); changed |= MaybeImproveInstructionSharding( std::move(new_sharding), reduce, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(reduce) == 1); } return changed; } auto get_maybe_tuple_sharding = [&](HloSharding sharding) { if (instruction->shape().IsArray()) { return sharding; } std::vector<HloSharding> tuple(instruction->shape().tuple_shapes_size(), std::move(sharding)); return HloSharding::Tuple(instruction->shape(), tuple); }; absl::c_any_of(instruction->dimensions(), [operand](int64_t dim) { return operand->sharding().tile_assignment().dim(dim) > 1; }))) { absl::StatusOr<bool> ProcessShardingInstruction( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads, bool replace_sharding_with_copy, absl::flat_hash_map<const HloInstruction*, std::vector<int64_t>>* unspecified_dims, std::vector<HloSharding>* saved_root_shardings, absl::flat_hash_map<int64_t, HloSharding>* saved_parameter_shardings, absl::flat_hash_map<HloInstruction*, int64_t>* instruction_to_shard_group_id, absl::flat_hash_map<int64_t, absl::flat_hash_set<HloInstruction*>>* shard_group_id_to_shard_as_group, absl::flat_hash_map<int64_t, absl::flat_hash_set<HloInstruction*>>* shard_group_id_to_shard_like_group, const std::vector<bool>* allow_spmd_sharding_propagation_to_parameters_vector) { bool changed = false; const bool use_shard_group = instruction_to_shard_group_id && shard_group_id_to_shard_as_group && shard_group_id_to_shard_like_group; // Process shard group instruction and returns if current instruction needs // to be removed. auto process_shard_group_instruction = [&](HloInstruction* instruction, bool replaced_with_copy) -> absl::StatusOr<bool> { // Run shard group processing IFF it's not CSE prevention. if (replace_sharding_with_copy) { if (use_shard_group && instruction->has_sharding() && instruction->sharding().IsShardGroup()) { if (instruction->IsCustomCall("Sharding")) { CHECK(instruction->operand(0)->opcode() != HloOpcode::kParameter || (allow_spmd_sharding_propagation_to_parameters_vector && allow_spmd_sharding_propagation_to_parameters_vector->size() == module->entry_computation()->num_parameters() && allow_spmd_sharding_propagation_to_parameters_vector->at( instruction->operand(0)->parameter_number()))); } if (instruction->IsCustomCall("Sharding") && !replaced_with_copy) { // Pass shard group to operand sharding custom-call if it's not // replaced with a copy, meaning that the shardings are to annotate // shard_group. HloSharding operand_sharding = instruction->operand(0)->has_sharding() ? instruction->operand(0)->sharding() : HloSharding::Unknown(); operand_sharding.SetShardGroup( instruction->sharding().GetShardGroup()); instruction->mutable_operand(0)->set_sharding( std::move(operand_sharding)); return true; } else { // Otherwise store the shard group relations. const int64_t shard_group_id = instruction->sharding().GetShardGroup().shard_group_id; (*instruction_to_shard_group_id)[instruction] = shard_group_id; if (instruction->sharding().IsShardAs()) { auto& shard_as_group = (*shard_group_id_to_shard_as_group)[shard_group_id]; if (!shard_as_group.empty()) { CHECK(ShapeUtil::SameDimensions( instruction->shape(), (*shard_as_group.begin())->shape())) << "Instruction: " << instruction->ToString() << " has different shape from the shapes of the other " "instructions within the same shard_as group: " << (*shard_as_group.begin())->shape().ToString(); } shard_as_group.insert(instruction); } else { auto& shard_like_group = (*shard_group_id_to_shard_like_group)[shard_group_id]; if (!shard_like_group.empty()) { CHECK(ShapeUtil::SameDimensions( instruction->shape(), (*shard_like_group.begin())->shape())) << "Instruction: " << instruction->ToString() << " has different shape from the shapes of the other " "instructions within the same shard_like group: " << (*shard_like_group.begin())->shape().ToString(); } shard_like_group.insert(instruction); } HloSharding sharding = instruction->sharding(); sharding.ClearShardGroup(); instruction->set_sharding(std::move(sharding)); } } } return false; }; for (HloComputation* computation : module->computations(execution_threads)) { auto instructions = computation->MakeInstructionPostOrder(); for (auto it = instructions.rbegin(); it != instructions.rend(); ++it) { HloInstruction* instruction = *it; if (instruction->IsCustomCall("Sharding")) { HloSharding original_sharding = instruction->sharding(); TF_RET_CHECK(instruction->has_sharding()) << "Sharding instruction must have a sharding attribute"; VLOG(3) << "ProcessShardingInstruction: " << instruction->ToString(); std::vector<int64_t> unspec_dims; TF_RETURN_IF_ERROR(sharding_op_util::ParseAttributes( Cast<HloCustomCallInstruction>(instruction)->opaque(), &unspec_dims)); bool replaced_with_copy = replace_sharding_with_copy && (!original_sharding.IsUnknown() || instruction->operand(0)->opcode() == HloOpcode::kParameter); // Replace the sharding instruction with a copy node so that it does not // need special handling. if (replaced_with_copy) { auto copy = computation->AddInstruction(HloInstruction::CreateUnary( instruction->shape(), HloOpcode::kCopy, instruction->mutable_operand(0))); TF_ASSIGN_OR_RETURN( std::ignore, computation->ReplaceInstruction( instruction, copy, /*preserve_sharding=*/false, /*relay_control_dependency=*/false, /*remove_unused_operands=*/false)); copy->set_sharding(std::move(original_sharding)); instruction = copy; changed = true; } TF_ASSIGN_OR_RETURN( bool shard_group_remove_instruction, process_shard_group_instruction(instruction, replaced_with_copy)); if (!unspec_dims.empty()) { absl::c_sort(unspec_dims); unspecified_dims->emplace(instruction, std::move(unspec_dims)); } else if (!instruction->operand(0)->has_sharding()) { instruction->mutable_operand(0)->set_sharding( instruction->sharding()); } if (shard_group_remove_instruction) { TF_ASSIGN_OR_RETURN(std::ignore, computation->ReplaceInstruction( instruction, instruction->mutable_operand(0), /*preserve_sharding=*/false, /*relay_control_dependency=*/false, /*remove_unused_operands=*/false)); } } else { TF_ASSIGN_OR_RETURN(std::ignore, process_shard_group_instruction( instruction, /*replaced_with_copy=*/false)); } } } // Save the original shardings of parameters/outputs. HloInstruction* root_instr = module->entry_computation()->root_instruction(); if (saved_root_shardings != nullptr && root_instr->shape().IsTuple() && root_instr->has_sharding()) { saved_root_shardings->reserve( root_instr->sharding().tuple_elements().size()); for (const HloSharding& sharding : root_instr->sharding().tuple_elements()) { saved_root_shardings->push_back(sharding); } } if (saved_parameter_shardings != nullptr) { auto params = module->entry_computation()->parameter_instructions(); for (int64_t i = 0; i < params.size(); ++i) { if (params[i]->has_sharding()) { saved_parameter_shardings->insert({i, params[i]->sharding()}); } } } return changed; } [&](HloInstruction* instruction, bool replaced_with_copy) -> absl::StatusOr<bool> { // Run shard group processing IFF it's not CSE prevention. if (replace_sharding_with_copy) { if (use_shard_group && instruction->has_sharding() && instruction->sharding().IsShardGroup()) { if (instruction->IsCustomCall("Sharding")) { CHECK(instruction->operand(0)->opcode() != HloOpcode::kParameter || (allow_spmd_sharding_propagation_to_parameters_vector && allow_spmd_sharding_propagation_to_parameters_vector->size() == module->entry_computation()->num_parameters() && allow_spmd_sharding_propagation_to_parameters_vector->at( instruction->operand(0)->parameter_number()))); } if (instruction->IsCustomCall("Sharding") && !replaced_with_copy) { // Pass shard group to operand sharding custom-call if it's not // replaced with a copy, meaning that the shardings are to annotate // shard_group. HloSharding operand_sharding = instruction->operand(0)->has_sharding() ? instruction->operand(0)->sharding() : HloSharding::Unknown(); operand_sharding.SetShardGroup( instruction->sharding().GetShardGroup()); instruction->mutable_operand(0)->set_sharding( std::move(operand_sharding)); return true; } else { // Otherwise store the shard group relations. const int64_t shard_group_id = instruction->sharding().GetShardGroup().shard_group_id; (*instruction_to_shard_group_id)[instruction] = shard_group_id; if (instruction->sharding().IsShardAs()) { auto& shard_as_group = (*shard_group_id_to_shard_as_group)[shard_group_id]; if (!shard_as_group.empty()) { CHECK(ShapeUtil::SameDimensions( instruction->shape(), (*shard_as_group.begin())->shape())) << "Instruction: " << instruction->ToString() << " has different shape from the shapes of the other " "instructions within the same shard_as group: " << (*shard_as_group.begin())->shape().ToString(); } shard_as_group.insert(instruction); } else { auto& shard_like_group = (*shard_group_id_to_shard_like_group)[shard_group_id]; if (!shard_like_group.empty()) { CHECK(ShapeUtil::SameDimensions( instruction->shape(), (*shard_like_group.begin())->shape())) << "Instruction: " << instruction->ToString() << " has different shape from the shapes of the other " "instructions within the same shard_like group: " << (*shard_like_group.begin())->shape().ToString(); } shard_like_group.insert(instruction); } HloSharding sharding = instruction->sharding(); sharding.ClearShardGroup(); instruction->set_sharding(std::move(sharding)); } } } return false; }; VLOG(3) << "ProcessShardingInstruction: " << instruction->ToString(); int64_t ComputeNonRootUsers(const HloInstruction* instr) { int64_t non_root_users = instr->users().size(); for (int i = 0; i < instr->users().size(); ++i) { if (instr->users()[i] == instr->parent()->root_instruction()) { --non_root_users; } } return non_root_users; } /*static*/ absl::Status ShardingPropagation::NormalizeDomain( const DomainMetadata::Domain& domain, const DomainMetadata* metadata) { if (metadata != nullptr) { TF_ASSIGN_OR_RETURN(const auto& sharding_metadata, ShardingMetadata::ToShardingMetadata(metadata)); const auto& sharding = sharding_metadata->sharding(); if (sharding != nullptr) { bool is_spatially_partitioned = !sharding->HasUniqueDevice(); if (sharding->IsTuple()) { is_spatially_partitioned = absl::c_any_of( sharding->tuple_elements(), [](const HloSharding& s) { return !s.HasUniqueDevice(); }); } if (is_spatially_partitioned) { for (HloInstruction* d : domain.exit_domains) { HloInstruction* operand = d->mutable_operand(0); // Set sharding only if it is different. We don't overwrite the // metadata if it has the same sharding besides metadata. if (!operand->has_sharding() || operand->sharding() != *sharding) { HloSharding operand_sharding = *sharding; if (operand->shape().IsTuple() && !sharding->IsTuple()) { // Expand sharding into tuple sharding per // CloneShardingForDomain() in // third_party/tensorflow/compiler/xla/hlo/ir/hlo_sharding_metadata.cc operand_sharding = HloSharding::SingleTuple(operand->shape(), *sharding); } operand->set_sharding(std::move(operand_sharding)); } } return absl::OkStatus(); } } } return ShardingMetadata::NormalizeShardingDomain(domain, metadata); } std::optional<HloSharding> ShardingPropagation::GetShardingFromUser( const HloInstruction& instruction, const HloInstruction& user, int64_t aggressiveness, bool is_spmd, const CallGraph& call_graph, const CustomCallShardingHelper* sharding_helper) { if (!CanPropagateThroughAtAggressiveLevel(user, aggressiveness)) { return std::nullopt; } if (!hlo_sharding_util::IsSpatiallyPartitioned(&user)) { return std::nullopt; } const bool may_combine_partial_sharding = is_spmd && aggressiveness > 0; switch (user.opcode()) { case HloOpcode::kBroadcast: { return InferBroadcastOperandSharding(user, is_spmd); } case HloOpcode::kConcatenate: { if (aggressiveness == 0) { return std::nullopt; } if (user.sharding().IsReplicated()) { return user.sharding(); } const int64_t cdim = user.concatenate_dimension(); auto& tile_assignment = user.sharding().tile_assignment(); if (tile_assignment.dim(cdim) == 1) { // If we are concatenating along a non-sharded dimension then the // operands should have the same sharding as the result. return user.sharding(); } if (is_spmd) { // SPMD doesn't support tiling with part of the devices. Return the same // sharding. return user.sharding(); } // If we are concatenating along a sharded dimension then we want the // operands to be distributed among the devices their data is used. int64_t start_offset = 0; for (HloInstruction* op : user.operands()) { if (op == &instruction) { break; } start_offset += op->shape().dimensions(cdim); } const int64_t tile_shape = CeilOfRatio( user.shape().dimensions(cdim), tile_assignment.dimensions()[cdim]); std::vector<int64_t> start_indices(tile_assignment.num_dimensions()); std::vector<int64_t> end_indices(tile_assignment.dimensions().begin(), tile_assignment.dimensions().end()); start_indices[cdim] = start_offset / tile_shape; end_indices[cdim] = CeilOfRatio( start_offset + instruction.shape().dimensions(cdim), tile_shape); auto new_tile_assignment = tile_assignment.array().Slice(start_indices, end_indices); if (new_tile_assignment.num_elements() == 1) { return HloSharding::AssignDevice(*new_tile_assignment.begin(), user.sharding().metadata()); } return HloSharding::Tile(std::move(new_tile_assignment), user.sharding().metadata()); } case HloOpcode::kConvolution: { auto dot_dims = dot_as_convolution_util::ParseConvolutionDimsInfo(&user); if (dot_dims.conv_spatial_dims.empty()) { int64_t op_idx = user.operand_index(&instruction); return hlo_sharding_util::InferDotOperandSharding( &user, op_idx, dot_dims, /*consider_other_operand=*/true, may_combine_partial_sharding); } return std::nullopt; } case HloOpcode::kDynamicSlice: case HloOpcode::kDynamicUpdateSlice: { if (aggressiveness == 0) { return std::nullopt; } if (user.sharding().IsReplicated()) { return user.sharding(); } if (user.opcode() == HloOpcode::kDynamicUpdateSlice && &instruction == user.operand(0)) { return user.sharding(); } const HloInstruction* operand = user.opcode() == HloOpcode::kDynamicSlice ? user.operand(0) : user.operand(1); if (&instruction != operand) { return std::nullopt; } if (is_spmd) { return user.sharding(); } const auto& tile_assignment = user.sharding().tile_assignment(); for (int64_t i = 0; i < user.shape().rank(); ++i) { if (tile_assignment.dim(i) > 1 && user.shape().dimensions(i) != operand->shape().dimensions(i)) { return std::nullopt; } } return user.sharding(); } case HloOpcode::kReduceWindow: { auto* reduce_window = Cast<HloReduceWindowInstruction>(&user); if (!absl::c_linear_search(reduce_window->inputs(), &instruction)) { return std::nullopt; } if (reduce_window->shape().IsTuple()) { auto sub_sharding = reduce_window->sharding().GetSubSharding( reduce_window->shape(), {reduce_window->operand_index(&instruction)}); return sub_sharding; } return reduce_window->sharding(); } case HloOpcode::kReshape: { return hlo_sharding_util::PropagateShardingThroughReshape( user.shape(), instruction.shape(), user.sharding()); } case HloOpcode::kPad: { if (&instruction != user.operand(0)) { return std::nullopt; } return user.sharding(); } case HloOpcode::kSlice: { return user.sharding(); } case HloOpcode::kTranspose: { // Calculate the dimension numbers for reversing the current transpose // and then use TransposeSharding to convert the output sharding to an // input sharding. std::vector<int64_t> reverse_dimensions(user.dimensions().size()); for (int64_t i = 0; i < user.dimensions().size(); ++i) { reverse_dimensions[user.dimensions(i)] = i; } return hlo_sharding_util::TransposeSharding(user.sharding(), reverse_dimensions); } case HloOpcode::kTuple: { auto sub_sharding = user.sharding().GetSubSharding( user.shape(), {user.operand_index(&instruction)}); // In case the instruction is used as the operands multiple times within // this tuple, we will return the most specific sharding and propagate up. for (int64_t i = 0; i < user.shape().tuple_shapes_size(); ++i) { if (user.operand(i) == &instruction) { // Only evaluate GetSubSharding if this operand is of interest, // as it is relatively expensive. HloSharding alternative_sub_sharding = user.sharding().GetSubSharding(user.shape(), {i}); if (hlo_sharding_util::IsShardingMoreSpecific( alternative_sub_sharding, sub_sharding)) { sub_sharding = alternative_sub_sharding; } } } return sub_sharding; } case HloOpcode::kGetTupleElement: { int64_t sharding_index = 0; for (int i = 0; i < instruction.shape().tuple_shapes_size(); ++i) { if (i == user.tuple_index()) { break; } if (instruction.shape().tuple_shapes(i).IsArray()) { sharding_index += 1; } else { sharding_index += ShapeUtil::GetLeafCount(instruction.shape().tuple_shapes(i)); } } if (user.shape().IsArray()) { // Use ReplicateAllDataDims instead of HloSharding::Replicate() to // preserve manual subgroups. HloSharding new_sharding = instruction.has_sharding() ? instruction.sharding() : HloSharding::SingleTuple( instruction.shape(), hlo_sharding_util::ReplicateAllDataDims(user.sharding())); new_sharding.tuple_elements()[sharding_index] = user.sharding(); return new_sharding; } else { if (user.sharding().tuple_elements().empty()) { return std::nullopt; } HloSharding new_sharding = instruction.has_sharding() ? instruction.sharding() : HloSharding::SingleTuple( instruction.shape(), hlo_sharding_util::ReplicateAllDataDims( user.sharding().tuple_elements()[0])); for (int64_t i = 0; i < user.sharding().tuple_elements().size(); ++i) { new_sharding.tuple_elements()[sharding_index + i] = user.sharding().tuple_elements()[i]; } return new_sharding; } } case HloOpcode::kDot: { int64_t op_idx = user.operand_index(&instruction); auto dnums = dot_as_convolution_util::ParseDotGeneralFromDot(&user); return hlo_sharding_util::InferDotOperandSharding( &user, op_idx, dnums, /*consider_other_operand=*/true, may_combine_partial_sharding); } case HloOpcode::kReduce: { if (instruction.shape().rank() == 0) { return std::nullopt; } auto user_sharding = user.shape().IsTuple() ? user.sharding().GetSubSharding( user.shape(), {user.operand_index(&instruction)}) : user.sharding(); if (!user_sharding.IsTileMaximal()) { std::vector<int64_t> target_tile_assignment_dimensions( instruction.shape().rank() + (user_sharding.ReplicateOnLastTileDim() ? 1 : 0) + user_sharding.subgroup_types().size()); const auto& dimensions = user.dimensions(); int64_t next_output_dim = 0; for (int64_t i = 0; i < target_tile_assignment_dimensions.size(); ++i) { if (absl::c_find(dimensions, i) == dimensions.end()) { target_tile_assignment_dimensions[i] = user_sharding.tile_assignment().dim(next_output_dim++); } else { target_tile_assignment_dimensions[i] = 1; } } auto tile_assignment = user_sharding.tile_assignment().Reshape( target_tile_assignment_dimensions); user_sharding = user_sharding.ReplicateOnLastTileDim() ? HloSharding::PartialTile(tile_assignment, user_sharding.metadata()) : HloSharding::Subgroup(tile_assignment, user_sharding.subgroup_types(), user_sharding.metadata()); } // Try to merge with sharding from other operands if they can improve // current sharding. const auto* reduce = Cast<const HloReduceInstruction>(&user); for (const HloInstruction* operand : reduce->inputs()) { if (operand != &instruction && operand->has_sharding()) { hlo_sharding_util::MergeShardingIfCompatible( operand->sharding(), user_sharding.NumTiles() + 1, &user_sharding); } } return user_sharding; } case HloOpcode::kSort: { HloSharding user_sharding = user.sharding(); if (user_sharding.IsTuple()) { return user_sharding.GetSubSharding(user.shape(), {user.operand_index(&instruction)}); } return user_sharding; } case HloOpcode::kReverse: { return hlo_sharding_util::ReverseSharding(user.sharding(), user.dimensions()); } case HloOpcode::kOutfeed: { if (&instruction != user.operand(0)) { return std::nullopt; } std::vector<Shape> operand_shapes(user.operand_count()); for (int i = 0; i < user.operand_count(); ++i) { operand_shapes[i] = user.operand(i)->shape(); } return user.sharding().GetSubSharding( ShapeUtil::MakeTupleShape(operand_shapes), {0}); } case HloOpcode::kGather: { if (&instruction == user.operand(1)) { return hlo_sharding_util:: GatherIndexShardingFromOutputIndexPassthroughDimensions( user.sharding(), &user); } if (is_spmd) { return hlo_sharding_util::GatherOperandShardingFromOutput( user.sharding(), user, call_graph); } return std::nullopt; } case HloOpcode::kScatter: { auto& scatter_user = *Cast<HloScatterInstruction>(&user); const int64_t operand_count = scatter_user.scatter_operand_count(); auto scatter_operands = scatter_user.scatter_operands(); auto scatter_indices = scatter_user.scatter_indices(); auto scatter_updates = scatter_user.scatter_updates(); // Infer sharding for scatter operand. const int64_t operand_index = absl::c_find(scatter_operands, &instruction) - scatter_operands.cbegin(); if (operand_index < operand_count) { return user.sharding().IsTuple() ? user.sharding().GetSubSharding( user.shape(), {operand_index}) : user.sharding(); } // Infer sharding for scatter indices. if (&instruction == scatter_indices) { std::vector<const HloInstruction*> partitioned_updates; for (const HloInstruction* update : scatter_updates) { if (hlo_sharding_util::IsSpatiallyPartitioned(update)) { partitioned_updates.push_back(update); } } if (partitioned_updates.empty()) { return std::nullopt; } std::vector<HloSharding> shardings; absl::c_transform( partitioned_updates, std::back_inserter(shardings), [&scatter_user](const HloInstruction* update) { return hlo_sharding_util:: ScatterIndexShardingFromUpdateIndexPassthroughDimensions( update->sharding(), &scatter_user); }); return hlo_sharding_util::FindCommonSharding(shardings); } // Infer sharding for scatter update. const int64_t update_index = absl::c_find(scatter_updates, &instruction) - scatter_updates.cbegin(); CHECK_LE(update_index, operand_count); auto from_indices = hlo_sharding_util::IsSpatiallyPartitioned(scatter_indices) ? hlo_sharding_util:: ScatterUpdateShardingFromIndexIndexPassthroughDimensions( scatter_indices->sharding(), &scatter_user) : HloSharding::Replicate(); if (is_spmd) { auto from_output = hlo_sharding_util::ScatterUpdateShardingFromOutput( user.sharding().IsTuple() ? user.sharding().GetSubSharding(user.shape(), {update_index}) : user.sharding(), scatter_user, call_graph); if (from_output.has_value()) { // Use sharding from output as primary sharding since it prioritize // parallel sharding first as this is how it is in spmd_partitioner. hlo_sharding_util::MergeShardingIfCompatible( from_indices, from_output->NumTiles() + 1, &*from_output); if (!from_output->IsTileMaximal()) { return from_output; } } } if (!from_indices.IsTileMaximal()) { return from_indices; } return std::nullopt; } case HloOpcode::kCustomCall: { bool compatible_shapes = ShapeUtil::CompatibleIgnoringElementType( instruction.shape(), user.shape()); if (!compatible_shapes) { // Incompatible shapes, we will not propagate sharding. return std::nullopt; } if (!sharding_helper) { // No available sharding helper and shapes are compatible, we will // propagate sharding. return user.sharding(); } if (sharding_helper->CanPropagateShardingToOperands(&user)) { return user.sharding(); } return std::nullopt; } default: { // If the user output shape is compatible with the current instruction // shape excluding element type and the current instruction is supported // by spatial partitioning, then the user sharding can be used for // propagation to the current instruction. if (ShapeUtil::CompatibleIgnoringElementType(instruction.shape(), user.shape())) { return user.sharding(); } return std::nullopt; } } } [&scatter_user](const HloInstruction* update) { return hlo_sharding_util:: ScatterIndexShardingFromUpdateIndexPassthroughDimensions( update->sharding(), &scatter_user); }); bool AggressiveConcatOperandShardingCanPassThrough( const HloInstruction* concat_operand) { return ( hlo_sharding_util::IsSpatiallyPartitioned(concat_operand) && (concat_operand->has_sharding() && concat_operand->sharding().NumTiles() > 1) && concat_operand->opcode() == HloOpcode::kReshape && (concat_operand->operand(0)->opcode() == HloOpcode::kParameter || concat_operand->operand(0)->opcode() == HloOpcode::kGetTupleElement)); } bool InferDynamicSliceOrDynamicUpdateSliceShardingFromOperands( HloInstruction* instruction, int64_t aggressiveness, bool may_combine_partial_sharding) { const HloInstruction* operand = instruction->opcode() == HloOpcode::kDynamicSlice ? instruction->operand(0) : instruction->operand(1); auto slice_dim_is_sharded = [&]() { if (!hlo_sharding_util::IsSpatiallyPartitioned(operand) || operand->sharding().IsManual() || operand->sharding().NumTiles() == 1) { return false; } for (int64_t i = 0; i < instruction->shape().rank(); ++i) { const auto& tile_assignment = operand->sharding().tile_assignment(); if (tile_assignment.dim(i) > 1 && instruction->shape().dimensions(i) != operand->shape().dimensions(i)) { return true; } } return false; }; // Do not pass through sharding annotation at the first iteration // if slice dim is sharded. if (aggressiveness == 0 && slice_dim_is_sharded()) { return false; } auto propagate_slicing = [&]() { if (!hlo_sharding_util::IsSpatiallyPartitioned(operand)) { return false; } if (slice_dim_is_sharded()) { return false; } return MaybeImproveInstructionSharding( operand->sharding(), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); }; auto propagate_base = [&]() { if (instruction->opcode() != HloOpcode::kDynamicUpdateSlice) { return false; } if (!hlo_sharding_util::IsSpatiallyPartitioned(instruction->operand(0))) { return false; } return MaybeImproveInstructionSharding(instruction->operand(0)->sharding(), instruction, may_combine_partial_sharding); }; bool changed = propagate_slicing(); changed |= propagate_base(); return changed; } auto slice_dim_is_sharded = [&]() { if (!hlo_sharding_util::IsSpatiallyPartitioned(operand) || operand->sharding().IsManual() || operand->sharding().NumTiles() == 1) { return false; } for (int64_t i = 0; i < instruction->shape().rank(); ++i) { const auto& tile_assignment = operand->sharding().tile_assignment(); if (tile_assignment.dim(i) > 1 && instruction->shape().dimensions(i) != operand->shape().dimensions(i)) { return true; } } return false; }; auto propagate_slicing = [&]() { if (!hlo_sharding_util::IsSpatiallyPartitioned(operand)) { return false; } if (slice_dim_is_sharded()) { return false; } return MaybeImproveInstructionSharding( operand->sharding(), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); }; auto propagate_base = [&]() { if (instruction->opcode() != HloOpcode::kDynamicUpdateSlice) { return false; } if (!hlo_sharding_util::IsSpatiallyPartitioned(instruction->operand(0))) { return false; } return MaybeImproveInstructionSharding(instruction->operand(0)->sharding(), instruction, may_combine_partial_sharding); }; bool ShardingPropagation::InferShardingFromShardGroup( HloInstruction* instruction, const ComputationMap& computation_map, int64_t aggressiveness, const absl::flat_hash_set<HloInstruction*>& shard_group) { if (!CanPropagateThroughAtAggressiveLevel(*instruction, aggressiveness)) { return false; } // Do not change manual sharding. if (instruction->has_sharding() && instruction->sharding().IsManual()) { return false; } // Do not propagate sharding to ShardBarrierTo custom-call. if (instruction->IsCustomCall(spmd::kShardBarrierTo)) { return false; } // Propagate manual sharding. if (!instruction->has_sharding() || instruction->sharding().IsTileMaximal()) { for (const HloInstruction* member : shard_group) { if (!member->has_sharding() || !member->sharding().IsManual() || member == instruction) { continue; } instruction->set_sharding(member->sharding()); return true; } } const bool may_combine_partial_sharding = is_spmd_ && aggressiveness > 0; bool changed = false; for (const HloInstruction* member : shard_group) { // Do not propagate sharding from ShardBarrierFrom custom-call. if (member == instruction || member->IsCustomCall(spmd::kShardBarrierFrom)) { continue; } changed |= MaybeImproveInstructionSharding(member->sharding(), instruction, may_combine_partial_sharding); } return changed; } bool ShardingPropagation::InferShardingFromOperands( HloInstruction* instruction, const ComputationMap& computation_map, int64_t aggressiveness, const CallGraph& call_graph, const absl::flat_hash_set<absl::string_view>& execution_threads) { if (!CanPropagateThroughAtAggressiveLevel(*instruction, aggressiveness)) { return false; } // Do not change manual sharding. if (instruction->has_sharding() && instruction->sharding().IsManual()) { return false; } // Propagate manual sharding. Avoid tuple shaped HLOs that group independent // together. Reduce, ReduceWindow, and Sort can be tuples but the elements // are correlated, so we propagate manual sharding through them. // For custom-calls with manual operand, the default propagation logic will // just assign manual to the whole custom-call. const bool custom_call_condition = instruction->opcode() == HloOpcode::kCustomCall && instruction->shape().IsTuple(); // For asynchronous instructions with manual operand, we assign manual to the // whole instructions if the async_execution_thread is not in the // execution_threads. const bool async_instr_condition = instruction->IsAsynchronous() && !HloInstruction::IsThreadIncluded(instruction->async_execution_thread(), execution_threads); if ((!instruction->has_sharding() || instruction->sharding().IsTileMaximal()) && (instruction->shape().IsArray() || instruction->opcode() == HloOpcode::kReduce || instruction->opcode() == HloOpcode::kSort || instruction->opcode() == HloOpcode::kReduceWindow || custom_call_condition || async_instr_condition)) { for (const HloInstruction* op : instruction->operands()) { if (!op->has_sharding() || !op->sharding().IsManual()) continue; // Do not pass through manual sharding to SPMDShardToFullShape. if (instruction->IsCustomCall("SPMDShardToFullShape")) { return false; } // Do not pass through manual sharding to concat or dynamic slice when // aggressiveneess is 0. if (aggressiveness == 0 && (instruction->opcode() == HloOpcode::kConcatenate || instruction->opcode() == HloOpcode::kDynamicSlice)) { return false; } instruction->set_sharding( HloSharding::Manual(op->sharding().metadata()) .NormalizeTupleSharding(instruction->shape())); return true; } } const bool may_combine_partial_sharding = is_spmd_ && aggressiveness > 0; if (!SupportSpatialPartitioning( instruction, computation_map, is_spmd_, allow_spmd_sharding_propagation_to_output_, /*allow_spmd_sharding_propagation_to_parameters=*/false, sharding_helper_.get())) { // If an array shaped HLO doesn't support spatial partitioning but at least // one of its operand is replicated then we make the HLO replicated as well. if (instruction->shape().IsTuple() || instruction->operand_count() == 0 || instruction == instruction->parent()->root_instruction() || instruction->HasSideEffect()) { return false; } for (const HloInstruction* op : instruction->operands()) { if (op->has_sharding() && op->sharding().IsTileMaximal() && !op->sharding().HasUniqueDevice()) { return MaybeImproveInstructionSharding(op->sharding(), instruction, may_combine_partial_sharding); } } return false; } auto get_maybe_tuple_sharding = [&](HloSharding sharding) { if (instruction->shape().IsArray()) { return sharding; } std::vector<HloSharding> tuple(instruction->shape().tuple_shapes_size(), std::move(sharding)); return HloSharding::Tuple(instruction->shape(), tuple); }; switch (instruction->opcode()) { case HloOpcode::kGetTupleElement: { const HloInstruction* operand = instruction->operand(0); if (!hlo_sharding_util::IsSpatiallyPartitioned(operand)) { return false; } HloSharding new_sharding = operand->sharding().GetSubSharding( operand->shape(), {instruction->tuple_index()}); if (new_sharding.IsManual()) { instruction->set_sharding(std::move(new_sharding)); return true; } return MaybeImproveInstructionSharding( std::move(new_sharding), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); } case HloOpcode::kTuple: { if (absl::c_none_of( instruction->operands(), [](const HloInstruction* hlo) { return hlo_sharding_util::IsSpatiallyPartitioned(hlo); })) { // None of the operands have a spatially partitioned sharding. return false; } const Shape& shape = instruction->shape(); // Go through each operand and if the operand has a sharding that is // better than the current sharding for that tuple element then update // it. If the current sharding does not exist, assume its replicated. std::vector<HloSharding> sub_shardings; if (instruction->has_sharding()) { sub_shardings = instruction->sharding().tuple_elements(); } else { // If instruction does not have a sharding, assume its replicated to // allow refinement. sub_shardings.assign(HloSharding::RequiredLeaves(shape), HloSharding::Replicate()); } // This is required to allow manual sharding on operands to be propagated // to the tuple. hlo_sharding_util::IsShardingMoreSpecific() returns false // if any of the shardings involved is manual, so using it directly will // prevent manual sharding on an operand to be propagated to the tuple // when it has no existing sharding. auto is_more_specific = [instruction](const HloSharding& operand_sharding, const HloSharding& existing) { // If the instruction originally had no sharding, always prefer operand // sharding. return !instruction->has_sharding() || hlo_sharding_util::IsShardingMoreSpecific(operand_sharding, existing); }; int64_t sub_sharding_index = 0; for (int64_t i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const HloInstruction* operand = instruction->operand(i); if (operand->has_sharding()) { if (operand->shape().IsTuple()) { for (int64_t j = 0, e = ShapeUtil::GetLeafCount(operand->shape()); j < e; ++j) { if (is_more_specific(operand->sharding().tuple_elements()[j], sub_shardings[sub_sharding_index + j])) { sub_shardings[sub_sharding_index + j] = operand->sharding().tuple_elements()[j]; } } } else { std::optional<HloSharding> op_sharding = hlo_sharding_util::GetOutputSharding(operand); CHECK(op_sharding.has_value()) << "Expected sharding for " << operand->ToString(); if (is_more_specific(op_sharding.value(), sub_shardings[sub_sharding_index])) { sub_shardings[sub_sharding_index] = op_sharding.value(); } } } sub_sharding_index += ShapeUtil::GetLeafCount(operand->shape()); } HloSharding new_sharding = HloSharding::Tuple(shape, sub_shardings); if (!instruction->has_sharding() || new_sharding != instruction->sharding()) { instruction->set_sharding(std::move(new_sharding)); return true; } return false; } case HloOpcode::kReduce: { // Reduce could have a tuple shape, where the first half of operands are // the arrays to reduce, and the second half of operands are the init // values. return InferReduceShardingFromOperand( instruction, may_combine_partial_sharding, is_spmd_); } case HloOpcode::kBroadcast: { // Make forward propagation through broadcast low priority to avoid // resharding after broadcast. if (aggressiveness < 3) { return false; } const HloInstruction* op = instruction->operand(0); if (!hlo_sharding_util::IsSpatiallyPartitioned(op) || op->sharding().IsReplicated()) { return false; } // The output will be tiled along the broadcasted dimension the same way // as the input for the broadcast while the other dimensions are kept // non-tiled. std::vector<int64_t> target_tile_assignment_dimensions; const auto& dimensions = instruction->dimensions(); for (int64_t i = 0; i < instruction->shape().rank(); ++i) { auto it = absl::c_find(dimensions, i); if (it == dimensions.end()) { target_tile_assignment_dimensions.push_back(1); } else { const int64_t source_dim = std::distance(dimensions.begin(), it); target_tile_assignment_dimensions.push_back( op->sharding().tile_assignment().dim(source_dim)); } } for (int64_t i = op->sharding().TiledDataRank(); i < op->sharding().tile_assignment().num_dimensions(); ++i) { target_tile_assignment_dimensions.push_back( op->sharding().tile_assignment().dim(i)); } auto new_tile_assignment = op->sharding().tile_assignment().Reshape( target_tile_assignment_dimensions); HloSharding new_sharding = op->sharding().ReplicateOnLastTileDim() ? HloSharding::PartialTile(new_tile_assignment, op->sharding().metadata()) : HloSharding::Subgroup(new_tile_assignment, op->sharding().subgroup_types(), op->sharding().metadata()); return MaybeImproveInstructionSharding( std::move(new_sharding), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ComputeNonRootUsers(instruction) == 1); } case HloOpcode::kConcatenate: { const HloInstruction* operand = PickRepresentativeOperand(instruction); if (!operand || !hlo_sharding_util::IsSpatiallyPartitioned(operand)) { return false; } if (aggressiveness == 0) { for (const HloInstruction* concat_operand : instruction->operands()) { if (!AggressiveConcatOperandShardingCanPassThrough(concat_operand)) { return false; } const auto& tile_assignment = concat_operand->sharding().tile_assignment(); for (int64_t i = 0; i < instruction->shape().rank(); ++i) { if (absl::c_linear_search(instruction->dimensions(), i) && tile_assignment.dim(i) > 1) { return false; } } } } return MaybeImproveInstructionSharding( operand->sharding(), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ComputeNonRootUsers(instruction) == 1); } case HloOpcode::kConvolution: return InferConvolutionShardingFromOperands( instruction, call_graph, aggressiveness, may_combine_partial_sharding, is_spmd_); case HloOpcode::kTranspose: { const HloInstruction* input = instruction->operand(0); if (!hlo_sharding_util::IsSpatiallyPartitioned(input)) { return false; } HloSharding sharding = hlo_sharding_util::TransposeSharding( input->sharding(), instruction->dimensions()); return MaybeImproveInstructionSharding( std::move(sharding), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ComputeNonRootUsers(instruction) == 1); } case HloOpcode::kReduceWindow: { auto* reduce_window = Cast<HloReduceWindowInstruction>(instruction); auto has_dilation = [](const WindowDimension& dimensions) { return dimensions.base_dilation() > 1 || dimensions.window_dilation() > 1; }; if (absl::c_any_of(instruction->window().dimensions(), has_dilation)) { VLOG(2) << "Not applying sharding to reduce window because dilatation " "isn't supported yet: " << reduce_window->ToString(); return false; } bool changed = false; for (HloInstruction* operand : reduce_window->inputs()) { if (!hlo_sharding_util::IsSpatiallyPartitioned(operand)) { continue; } changed |= MaybeImproveInstructionSharding( get_maybe_tuple_sharding(operand->sharding()), reduce_window, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); } return changed; } case HloOpcode::kSelectAndScatter: { // Shard according to first operand, as output keeps the same shape. const HloInstruction* lhs = instruction->operand(0); if (!hlo_sharding_util::IsSpatiallyPartitioned(lhs)) { return false; } auto has_base_dilation = [](const WindowDimension& dimensions) { return dimensions.base_dilation() > 1; }; if (absl::c_any_of(instruction->window().dimensions(), has_base_dilation)) { VLOG(2) << "Not applying sharding to select-and-scatter because " "base dilation isn't supported yet: " << instruction->ToString(); return false; } return MaybeImproveInstructionSharding( lhs->sharding(), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ComputeNonRootUsers(instruction) == 1); } case HloOpcode::kReshape: { if (!hlo_sharding_util::IsSpatiallyPartitioned(instruction->operand(0))) { return false; } HloSharding new_sharding = hlo_sharding_util::PropagateShardingThroughReshape( instruction->operand(0)->shape(), instruction->shape(), instruction->operand(0)->sharding()); return MaybeImproveInstructionSharding( std::move(new_sharding), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); return false; } case HloOpcode::kReverse: { const HloInstruction* operand = instruction->operand(0); if (!hlo_sharding_util::IsSpatiallyPartitioned(operand)) { return false; } return MaybeImproveInstructionSharding( hlo_sharding_util::ReverseSharding(operand->sharding(), instruction->dimensions()), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ComputeNonRootUsers(instruction) == 1); } case HloOpcode::kDot: { const auto& dnums = dot_as_convolution_util::ParseDotGeneralFromDot(instruction); return InferDotShardingFromOperands(instruction, call_graph, dnums, may_combine_partial_sharding, is_spmd_); } case HloOpcode::kParameter: { auto parent_it = computation_map.find(instruction->parent()); if (parent_it == computation_map.end()) { return false; } const HloInstruction* parent = parent_it->second; switch (parent->opcode()) { case HloOpcode::kConditional: { for (int64_t i = 1; i < parent->operand_count(); ++i) { if (parent->called_computations()[i - 1] == instruction->parent()) { if (parent->operand(i)->has_sharding()) { return MaybeImproveInstructionSharding( parent->operand(i)->sharding(), instruction, may_combine_partial_sharding); } return false; } } return false; } case HloOpcode::kCall: { int64_t i = instruction->parameter_number(); if (parent->operand(i)->has_sharding()) { return MaybeImproveInstructionSharding( parent->operand(i)->sharding(), instruction, may_combine_partial_sharding); } return false; } default: return false; } } case HloOpcode::kSort: { const HloInstruction* operand = PickRepresentativeOperand(instruction); if (!operand || !hlo_sharding_util::IsSpatiallyPartitioned(operand)) { return false; } HloSortInstruction* sort = DynCast<HloSortInstruction>(instruction); CHECK(sort); const int64_t sort_dim = sort->sort_dimension(); if (!operand->sharding().IsTileMaximal() && operand->sharding().tile_assignment().dim(sort_dim) != 1) { // In case of a sort operand sharded along the sort dimension, the // sharding is propagated only if there exists a free (unsharded) // dimension that we can later move the sharding into. if (!hlo_sharding_util::IsSortOperandShardingMovable(operand, sort_dim)) return false; } if (instruction->shape().IsTuple()) { return MaybeImproveInstructionSharding( HloSharding::SingleTuple(instruction->shape(), operand->sharding()), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); } else { return MaybeImproveInstructionSharding( operand->sharding(), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ ComputeNonRootUsers(instruction) == 1); } } case HloOpcode::kDynamicSlice: case HloOpcode::kDynamicUpdateSlice: { return InferDynamicSliceOrDynamicUpdateSliceShardingFromOperands( instruction, aggressiveness, may_combine_partial_sharding); } case HloOpcode::kGather: { bool changed = false; if (hlo_sharding_util::IsSpatiallyPartitioned(instruction->operand(1))) { HloSharding new_sharding = hlo_sharding_util:: GatherOutputShardingFromIndexIndexPassthroughDimensions( instruction->operand(1)->sharding(), instruction); changed |= MaybeImproveInstructionSharding( std::move(new_sharding), instruction, may_combine_partial_sharding); } if (is_spmd_) { auto gather_parallel_dims = hlo_sharding_util::GetGatherParallelBatchDims(*instruction, call_graph); if (gather_parallel_dims) { changed |= InferGatherParallelShardingFromOperands( instruction, *gather_parallel_dims, may_combine_partial_sharding); } if (hlo_sharding_util::IsSpatiallyPartitioned( instruction->operand(0))) { absl::Span<const int64_t> operand_parallel_dims; if (gather_parallel_dims) { operand_parallel_dims = absl::MakeConstSpan( gather_parallel_dims->operand_parallel_dims); } HloSharding filtered_operand_sharding = hlo_sharding_util::PartiallyReplicateTiledShardingOnDims( instruction->operand(0)->sharding(), operand_parallel_dims); auto maybe_from_data = hlo_sharding_util:: GatherOutputShardingFromOperandOperandPassthroughDimensions( filtered_operand_sharding, *instruction); if (maybe_from_data) { changed |= MaybeImproveInstructionSharding( std::move(*maybe_from_data), instruction, may_combine_partial_sharding); } } } return changed; } case HloOpcode::kScatter: { auto& scatter = *Cast<HloScatterInstruction>(instruction); const int64_t operand_count = scatter.scatter_operand_count(); auto scatter_operands = scatter.scatter_operands(); auto scatter_indices = scatter.scatter_indices(); auto scatter_updates = scatter.scatter_updates(); bool changed = false; if (is_spmd_) { for (int64_t i = 0; i != operand_count; ++i) { if (hlo_sharding_util::IsSpatiallyPartitioned(scatter_operands[i])) { changed |= MaybeImproveInstructionSubSharding( scatter_operands[i]->sharding(), instruction, {i}, may_combine_partial_sharding); } } if (!hlo_sharding_util::IsSpatiallyPartitioned(scatter_indices) && absl::c_none_of(scatter_updates, [](const HloInstruction* update) { return hlo_sharding_util::IsSpatiallyPartitioned(update); })) { return changed; } auto scatter_parallel_dims = hlo_sharding_util::GetScatterParallelBatchDims(*instruction, call_graph); if (scatter_parallel_dims) { changed |= InferScatterParallelShardingFromOperands( instruction, *scatter_parallel_dims, may_combine_partial_sharding); } for (int64_t i = 0; i != operand_count; ++i) { if (hlo_sharding_util::IsSpatiallyPartitioned(scatter_updates[i])) { auto maybe_from_update = hlo_sharding_util::ScatterOutputShardingFromUpdate( scatter_updates[i]->sharding(), scatter); if (maybe_from_update) { changed |= MaybeImproveInstructionSubSharding( std::move(*maybe_from_update), instruction, {i}, may_combine_partial_sharding); } } } } else { for (int64_t i = 0; i != operand_count; ++i) { changed |= MaybeImproveInstructionSubSharding( HloSharding::Replicate(), instruction, {i}, may_combine_partial_sharding); } } return changed; } case HloOpcode::kWhile: { if (!instruction->operand(0)->has_sharding()) { return false; } auto sharding = instruction->operand(0)->sharding(); if (instruction->has_sharding()) { hlo_sharding_util::MergeSharding(instruction->sharding(), &sharding, may_combine_partial_sharding); } return MaybeImproveInstructionSharding(std::move(sharding), instruction, may_combine_partial_sharding); } case HloOpcode::kCustomCall: { HloSharding inferred_operand_sharding = HloSharding::Replicate(); if (auto* partitioner = GetCustomCallPartitioner(instruction->custom_call_target()); partitioner && partitioner->IsCustomCallShardable(instruction)) { if (auto sharding = partitioner->InferShardingFromOperands(instruction)) { inferred_operand_sharding = *sharding; } else { return false; } } else if (sharding_helper_->IsCustomCallShardable(instruction)) { if (auto sharding = sharding_helper_->InferShardingFromOperands(instruction)) { inferred_operand_sharding = *sharding; } else { return false; } } else { const HloInstruction* operand = PickRepresentativeOperand(instruction); if (!operand || !hlo_sharding_util::IsSpatiallyPartitioned(operand)) { return false; } inferred_operand_sharding = operand->sharding(); } return MaybeImproveInstructionSharding( inferred_operand_sharding, instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ComputeNonRootUsers(instruction) == 1); } default: { if (instruction->IsElementwise() && may_combine_partial_sharding) { bool changed = false; for (auto operand : instruction->operands()) { if (hlo_sharding_util::IsSpatiallyPartitioned(operand)) { if (instruction->opcode() == HloOpcode::kRng) { // Rng is considered elementwise but has operands with different // shapes. changed |= MaybeImproveInstructionSharding( hlo_sharding_util::ReplicateAllDataDims( operand->sharding(), instruction->shape().rank()), instruction, may_combine_partial_sharding, ComputeNonRootUsers(instruction) == 1); continue; } changed |= MaybeImproveInstructionSharding( operand->sharding(), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ instruction->operands().size() == 1 && ComputeNonRootUsers(instruction) == 1); } } return changed; } const HloInstruction* operand = PickRepresentativeOperand(instruction); if (!operand || !hlo_sharding_util::IsSpatiallyPartitioned(operand)) { return false; } return MaybeImproveInstructionSharding( operand->sharding(), instruction, may_combine_partial_sharding, /*allow_aggressive_resharding=*/ComputeNonRootUsers(instruction) == 1); } } return false; } // NOLINT(readability/fn_size) auto get_maybe_tuple_sharding = [&](HloSharding sharding) { if (instruction->shape().IsArray()) { return sharding; } std::vector<HloSharding> tuple(instruction->shape().tuple_shapes_size(), std::move(sharding)); return HloSharding::Tuple(instruction->shape(), tuple); }; auto is_more_specific = [instruction](const HloSharding& operand_sharding, const HloSharding& existing) { // If the instruction originally had no sharding, always prefer operand // sharding. return !instruction->has_sharding() || hlo_sharding_util::IsShardingMoreSpecific(operand_sharding, existing); }; VLOG(2) << "Not applying sharding to reduce window because dilatation " VLOG(2) << "Not applying sharding to select-and-scatter because " bool ShardingPropagation::InferShardingFromUsers( HloInstruction* instruction, const ShardingPropagation::ComputationMap& computation_map, int64_t aggressiveness, bool is_spmd, const CustomCallShardingHelper* sharding_helper, const CallGraph& call_graph) { if (aggressiveness < 2 && instruction->opcode() == HloOpcode::kBroadcast) { return false; } // Do not change manual sharding. if (instruction->has_sharding() && instruction->sharding().IsManual()) { return false; } // Propagate manual sharding. if (!instruction->has_sharding() || instruction->sharding().IsTileMaximal()) { for (const HloInstruction* user : instruction->users()) { if (!user->has_sharding() || user->IsCustomCall("SPMDFullToShardShape")) continue; if (instruction->shape().IsArray() && user->sharding().IsManual()) { instruction->set_sharding( HloSharding::Manual(user->sharding().metadata())); return true; } else { std::optional<HloSharding> user_sharding = ShardingPropagation::GetShardingFromUser( *instruction, *user, aggressiveness, is_spmd, call_graph, sharding_helper); if (user_sharding && user_sharding->IsManual()) { instruction->set_sharding(std::move(*user_sharding)); return true; } } } } if (!SupportSpatialPartitioning( instruction, computation_map, is_spmd, /*allow_spmd_sharding_propagation_to_output=*/false, allow_spmd_sharding_propagation_to_parameters_, sharding_helper)) { return false; } bool improved_sharding = false; const bool may_combine_partial_sharding = is_spmd && aggressiveness > 0; for (const HloInstruction* user : instruction->users()) { std::optional<HloSharding> user_sharding = ShardingPropagation::GetShardingFromUser(*instruction, *user, aggressiveness, is_spmd, call_graph, sharding_helper); if (user_sharding && instruction->opcode() == HloOpcode::kCustomCall) { if (auto* partitioner = GetCustomCallPartitioner(instruction->custom_call_target())) { if (partitioner->IsCustomCallShardable(instruction)) { user_sharding = partitioner->PropagateUserSharding(instruction, user, *user_sharding); } } else if (sharding_helper->IsCustomCallShardable(instruction)) { user_sharding = sharding_helper->PropagateUserSharding( instruction, user, *user_sharding); } } if (user_sharding) { improved_sharding |= MaybeImproveInstructionSharding( std::move(*user_sharding), instruction, may_combine_partial_sharding); } } return improved_sharding; } absl::StatusOr<bool> ShardingPropagation::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { // Register custom-call partitioner for SharBarrierFrom and ShardBarrierTo. ABSL_CONST_INIT static absl::once_flag did_registration; absl::call_once(did_registration, [] { RegisterCustomCallPartitioner( spmd::kShardBarrierFrom, std::make_unique<spmd::ShardBarrierFromPartitioner>()); RegisterCustomCallPartitioner( spmd::kShardBarrierTo, std::make_unique<spmd::ShardBarrierToPartitioner>()); }); std::optional<absl::flat_hash_map<const HloInstruction*, HloSharding>> original_sharding; bool any_changed = false; // Preprocessing for CSE prevention propagation: record the original shardings // so that we can revert to them at the end, and only keep those on CSE // prevention instructions. if (cse_prevention_only_) { original_sharding.emplace(); for (auto computation : module->computations(execution_threads)) { for (auto instruction : computation->instructions()) { if (instruction->has_sharding()) { original_sharding->emplace(instruction, instruction->sharding()); } } } } else { // The current pass is not for CSE prevention, but we remove the shardings // added by previous passes for CSE prevention. for (auto computation : module->computations(execution_threads)) { for (auto instruction : computation->instructions()) { if (instruction->has_sharding() && IsCSEPreventionSharding(instruction->sharding())) { instruction->clear_sharding(); any_changed = true; } } } } any_changed |= propagate_metadata_ ? AssignShardingMetadata(module, execution_threads) : RemoveShardingMetadata(module, execution_threads); absl::flat_hash_map<const HloInstruction*, std::vector<int64_t>> unspecified_dims; std::vector<HloSharding> saved_root_shardings; absl::flat_hash_map<int64_t, HloSharding> saved_parameter_shardings; absl::flat_hash_map<HloInstruction*, int64_t> instruction_to_shard_group_id; absl::flat_hash_map<int64_t, absl::flat_hash_set<HloInstruction*>> shard_group_id_to_shard_as_group; absl::flat_hash_map<int64_t, absl::flat_hash_set<HloInstruction*>> shard_group_id_to_shard_like_group; TF_ASSIGN_OR_RETURN( bool changed, ProcessShardingInstruction( module, execution_threads, !cse_prevention_only_, &unspecified_dims, allow_spmd_sharding_propagation_to_output_ ? &saved_root_shardings : nullptr, allow_spmd_sharding_propagation_to_parameters_ ? &saved_parameter_shardings : nullptr, &instruction_to_shard_group_id, &shard_group_id_to_shard_as_group, &shard_group_id_to_shard_like_group, &allow_spmd_sharding_propagation_to_parameters_vector_)); any_changed |= changed; for (const auto& [shard_group_id, shard_as_group] : shard_group_id_to_shard_as_group) { VLOG(5) << "Shard-As group " << shard_group_id << " contains:"; for (auto instruction : shard_as_group) { VLOG(5) << " " << instruction->ToString(); } } for (const auto& [shard_group_id, shard_like_group] : shard_group_id_to_shard_like_group) { VLOG(5) << "Shard-Like group " << shard_group_id << " contains:"; for (auto instruction : shard_like_group) { VLOG(5) << " " << instruction->ToString(); } } // Check sizes of the given allow_spmd_sharding_propagation vectors if (allow_spmd_sharding_propagation_to_output_) { CHECK(!module->entry_computation()->root_instruction()->has_sharding() || allow_spmd_sharding_propagation_to_output_vector_.size() == 1 || module->entry_computation() ->root_instruction() ->sharding() .tuple_elements() .size() == allow_spmd_sharding_propagation_to_output_vector_.size()) << "allow-spmd-sharding-propagation-to-output-vector's size can be " "either 1 or the number of elements in the root tuple of entry " "computation."; } if (allow_spmd_sharding_propagation_to_parameters_) { auto is_same_sized_tuple = [](HloModule* module, int64_t size) { if (module->entry_computation()->num_parameters() != 1) { return false; } HloInstruction* param = module->entry_computation()->parameter_instruction(0); return param->shape().IsTuple() && size == param->shape().tuple_shapes_size(); }; auto size = allow_spmd_sharding_propagation_to_parameters_vector_.size(); CHECK(size == 1 || size == module->entry_computation()->num_parameters() || is_same_sized_tuple(module, size)) << "allow-spmd-sharding-propagation-to-parameters-vector's size can be " "either 1 or the number of parameters in the entry computation."; } // Association of partitionable embedded computations with their parent // instruction. ComputationMap computation_map; // Instructions that are related through a computation and need to share the // same sharding. auto get_related_instructions = [this](HloInstruction* inst) { if (inst->opcode() == HloOpcode::kWhile) { return std::vector<HloInstruction*>{ inst, inst->while_body()->root_instruction(), inst->while_body()->parameter_instruction(0), inst->while_condition()->parameter_instruction(0)}; } else if (inst->opcode() == HloOpcode::kConditional) { const auto& called_computations = inst->called_computations(); std::vector<HloInstruction*> comps; comps.reserve(called_computations.size() + 1); comps.push_back(inst); for (HloComputation* c : called_computations) { comps.push_back(c->root_instruction()); } return comps; } else if (inst->opcode() == HloOpcode::kCustomCall) { if (sharding_helper_ && sharding_helper_->IsCustomCallShardable(inst)) { return sharding_helper_->GetRelatedInstructions(inst); } else { return std::vector<HloInstruction*>{}; } } else if (inst->opcode() == HloOpcode::kCall) { HloComputation* callee = inst->called_computations().front(); return std::vector<HloInstruction*>{inst, callee->root_instruction()}; } else { CHECK(false); } }; // If instruction is a while, or the root or a parameter of a while body, // then propagate its sharding to the while instruction, to its body root, // and to its condition parameter. std::function<void(HloInstruction*, absl::flat_hash_set<HloInstruction*>*)> maybe_computation_propagation = [&](HloInstruction* instruction, absl::flat_hash_set<HloInstruction*>* changed) { auto propagate_to_instruction = [&](HloInstruction* search_inst) { auto related_instructions = get_related_instructions(search_inst); if (absl::c_count(related_instructions, instruction)) { for (HloInstruction* inst : related_instructions) { if (!inst->has_sharding() || inst->sharding() != instruction->sharding()) { VLOG(2) << "Add computation sharding: " << inst->name() << " " << instruction->sharding().ToString(); inst->copy_sharding(instruction); changed->insert(inst); maybe_computation_propagation(inst, changed); } } } }; if (instruction->opcode() == HloOpcode::kConditional || instruction->opcode() == HloOpcode::kWhile || instruction->opcode() == HloOpcode::kCustomCall || instruction->opcode() == HloOpcode::kCall) { propagate_to_instruction(instruction); } if (instruction->opcode() == HloOpcode::kParameter || instruction->parent()->root_instruction() == instruction) { auto it = computation_map.find(instruction->parent()); if (it != computation_map.end()) { propagate_to_instruction(it->second); } } }; for (auto computation : module->computations(execution_threads)) { for (auto instruction : computation->instructions()) { if (instruction->opcode() == HloOpcode::kWhile) { TF_RETURN_IF_ERROR( CheckAndUpdateDeviceAssignmentsInWhileBody(instruction)); } } } // Populate computation_map in order to associate while bodies to their // while instructions. for (auto computation : module->computations(execution_threads)) { for (auto instruction : computation->instructions()) { if (instruction->opcode() == HloOpcode::kWhile || instruction->opcode() == HloOpcode::kConditional || instruction->opcode() == HloOpcode::kCall) { // Check if any of the related instructions has sharding, in which case // propagate it to the other instructions, so they all share the same // sharding, in case the user didn't shard all of them. We don't check // that user shardings are consistent, because such check is already // done by HLO verifier. const HloInstruction* sharded_inst = nullptr; auto related_instructions = get_related_instructions(instruction); for (auto inst : related_instructions) { if (inst->has_sharding()) { sharded_inst = inst; break; } } if (sharded_inst != nullptr) { // Set the same sharding to all the other related instructions. for (auto inst : related_instructions) { inst->copy_sharding(sharded_inst); } } if (instruction->opcode() == HloOpcode::kWhile) { computation_map[instruction->while_body()] = instruction; } else { for (HloComputation* c : instruction->called_computations()) { computation_map[c] = instruction; } } } } } // Collect all pre-sharded instructions as we aren't allowed to modify their // sharding. absl::flat_hash_set<const HloInstruction*> provided_shardings; for (const HloComputation* computation : module->computations(execution_threads)) { for (const HloInstruction* inst : computation->instructions()) { if (inst->has_sharding() && inst != module->entry_computation()->root_instruction() && inst->opcode() != HloOpcode::kParameter && !inst->sharding().IsUnknown()) { provided_shardings.insert(inst); } } } if (!allow_spmd_sharding_propagation_to_output_ && (!module->entry_computation()->root_instruction()->has_sharding() || !module->entry_computation() ->root_instruction() ->sharding() .IsUnknown())) { // Consider the root instruction of the entry module as one with provided // sharding as its sharding have to match with the one expected by the host. provided_shardings.insert(module->entry_computation()->root_instruction()); } if (!allow_spmd_sharding_propagation_to_parameters_) { for (auto param : module->entry_computation()->parameter_instructions()) { if (param->has_sharding() && !param->sharding().IsUnknown()) { provided_shardings.insert(param); } } } // Replace all unknown shardings with replicated sharding for propagation. for (HloComputation* computation : module->computations(execution_threads)) { auto instructions = computation->MakeInstructionPostOrder(); for (auto it = instructions.rbegin(); it != instructions.rend(); ++it) { HloInstruction* instruction = *it; if (instruction->has_sharding() && instruction->sharding().IsUnknown()) { instruction->set_sharding( HloSharding::Replicate(instruction->sharding().metadata())); } } } // Iterate to a fixpoint that is guaranteed to be reached because we only // strictly improve the sharding of the graph and it can't be improved // indefinitely. int64_t iterations = 0; std::unique_ptr<CallGraph> call_graph = CallGraph::Build(module); auto run_to_fix_point = [&](int64_t aggressiveness, bool propagate_shard_group) { absl::flat_hash_set<const HloInstruction*> already_inferred_from_shard_group; absl::flat_hash_set<const HloInstruction*> already_inferred_from_operands; absl::flat_hash_set<const HloInstruction*> already_inferred_from_users; bool changed_last_iter = true; const bool may_merge_partial = is_spmd_ && aggressiveness > 0; while (changed_last_iter) { changed_last_iter = false; int64_t inferred_from_shard_group_counter = 0; int64_t inferred_from_operand_counter = 0; int64_t inferred_from_user_counter = 0; int64_t instruction_counter = 0; int64_t already_sharded_counter = 0; for (const HloComputation* computation : module->computations(execution_threads)) { VLOG(2) << "Consider computation: " << computation->name(); std::vector<HloInstruction*> instructions = computation->MakeInstructionPostOrder(); instruction_counter += instructions.size(); already_sharded_counter += absl::c_count_if( instructions, [](const HloInstruction* inst) { return inst->has_sharding(); }); auto clear_cache = [&](HloInstruction* hlo, HloInstruction* hlo_for_users = nullptr) { for (auto operand : hlo->operands()) { already_inferred_from_users.erase(operand); } if (hlo_for_users == nullptr) { hlo_for_users = hlo; } for (auto user : hlo_for_users->users()) { already_inferred_from_operands.erase(user); // If the user has called computations, then the parameter // instructions of these called computations are also removed from // already_inferred_from_operands. for (auto c : user->called_computations()) { for (auto parameter : c->parameter_instructions()) { already_inferred_from_operands.erase(parameter); } } } if (instruction_to_shard_group_id.contains(hlo)) { const int64_t shard_group_id = instruction_to_shard_group_id.at(hlo); const absl::flat_hash_set<HloInstruction*>& shard_group = shard_group_id_to_shard_as_group.contains(shard_group_id) ? shard_group_id_to_shard_as_group.at(shard_group_id) : shard_group_id_to_shard_like_group.at(shard_group_id); for (HloInstruction* member : shard_group) { if (member != hlo) { already_inferred_from_shard_group.erase(member); } } } }; // 1. Iterate the shard groups to take shardings from instructions of // the same group. if (propagate_shard_group) { for (HloInstruction* instruction : instructions) { if (already_inferred_from_shard_group.contains(instruction)) { continue; } if (!instruction_to_shard_group_id.contains(instruction)) { continue; } const int64_t shard_group_id = instruction_to_shard_group_id.at(instruction); const absl::flat_hash_set<HloInstruction*>& shard_group = shard_group_id_to_shard_as_group.contains(shard_group_id) ? shard_group_id_to_shard_as_group.at(shard_group_id) : shard_group_id_to_shard_like_group.at(shard_group_id); if (provided_shardings.contains(instruction)) { if (!may_merge_partial) { continue; } auto it = unspecified_dims.find(instruction); if (it != unspecified_dims.end() && InferUnspecifiedDimsFromShardGroup(instruction, it->second, shard_group)) { ++inferred_from_shard_group_counter; VLOG(2) << "Refined partial sharding (shard group): " << instruction->ToString(); clear_cache(instruction); already_inferred_from_shard_group.insert(instruction); changed_last_iter = true; } continue; } already_inferred_from_shard_group.insert(instruction); if (InferShardingFromShardGroup(instruction, computation_map, aggressiveness, shard_group)) { ++inferred_from_shard_group_counter; any_changed = true; VLOG(2) << "Add sharding (shard group): " << instruction->ToString(); absl::flat_hash_set<HloInstruction*> changed_in_comp_prop; maybe_computation_propagation(instruction, &changed_in_comp_prop); clear_cache(instruction); for (auto hlo : changed_in_comp_prop) { clear_cache(hlo); } changed_last_iter = true; } } } // 2. Iterate the HLO graph in post order taking shardings from // operands. for (HloInstruction* instruction : instructions) { if (already_inferred_from_operands.contains(instruction)) { continue; } if (provided_shardings.contains(instruction)) { if (!may_merge_partial) { continue; } auto it = unspecified_dims.find(instruction); HloInstruction* man_conversion_op_after; if (it != unspecified_dims.end() && InferUnspecifiedDimsFromOperand(instruction, it->second, &man_conversion_op_after)) { ++inferred_from_operand_counter; VLOG(2) << "Refined partial sharding (forward-pass): " << instruction->ToString(); clear_cache(instruction, man_conversion_op_after); already_inferred_from_operands.insert(instruction); changed_last_iter = true; } continue; } already_inferred_from_operands.insert(instruction); if (InferShardingFromOperands(instruction, computation_map, aggressiveness, *call_graph, execution_threads)) { ++inferred_from_operand_counter; any_changed = true; VLOG(2) << "Add sharding (forward-pass): " << instruction->ToString(); absl::flat_hash_set<HloInstruction*> changed_in_comp_prop; maybe_computation_propagation(instruction, &changed_in_comp_prop); clear_cache(instruction); for (auto hlo : changed_in_comp_prop) { clear_cache(hlo); } changed_last_iter = true; } } // 3. Iterate the HLO graph in reverse post order taking shardings from // users. for (auto it = instructions.rbegin(); it != instructions.rend(); ++it) { if ((*it)->IsCustomCall("SPMDFullToShardShape") || (*it)->IsCustomCall("SPMDShardToFullShape")) { // The manual conversion op is processed together with the sharding // op before it. If the conversion op is removed from cache, the // sharding op should also be removed. if (!already_inferred_from_users.contains(*it)) { already_inferred_from_users.erase((*it)->operand(0)); } } if (already_inferred_from_users.contains(*it)) { continue; } if (provided_shardings.contains(*it)) { if (!may_merge_partial) { continue; } auto uit = unspecified_dims.find(*it); HloInstruction* man_conversion_op_after; if (uit != unspecified_dims.end() && InferUnspecifiedDimsFromUsers( *it, uit->second, aggressiveness, is_spmd_, &man_conversion_op_after, *call_graph)) { ++inferred_from_user_counter; VLOG(2) << "Refined partial sharding (backward-pass): " << (*it)->ToString(); clear_cache(*it, man_conversion_op_after); already_inferred_from_users.insert(*it); if (man_conversion_op_after != nullptr) { already_inferred_from_users.insert(man_conversion_op_after); } changed_last_iter = true; } continue; } already_inferred_from_users.insert(*it); if (InferShardingFromUsers(*it, computation_map, aggressiveness, is_spmd_, sharding_helper_.get(), *call_graph)) { ++inferred_from_user_counter; any_changed = true; VLOG(2) << "Add sharding (backward-pass): " << (*it)->ToString(); absl::flat_hash_set<HloInstruction*> changed_in_comp_prop; maybe_computation_propagation(*it, &changed_in_comp_prop); clear_cache(*it); for (auto hlo : changed_in_comp_prop) { clear_cache(hlo); } changed_last_iter = true; } } } VLOG(1) << "Sharding propagation iteration " << iterations << ";" << "\n total instructions: " << instruction_counter << "\n instructions already sharded: " << already_sharded_counter << "\n shardings inferred from shard group: " << inferred_from_shard_group_counter << "\n shardings inferred from operands: " << inferred_from_operand_counter << "\n shardings inferred from users: " << inferred_from_user_counter << "\n aggressiveness: " << aggressiveness; ++iterations; } return absl::OkStatus(); }; for (int64_t aggressiveness = 0; aggressiveness < 4; ++aggressiveness) { TF_RETURN_IF_ERROR( run_to_fix_point(aggressiveness, /*propagate_shard_group=*/true)); } // Align the shardings from the same shard_as group so that they will adopt // the same sharding. for (const auto& [shard_as_group_id, shard_as_group] : shard_group_id_to_shard_as_group) { // If all the inferred shardings of the instructions from the same shard // group are compatible with each other, then we will merge all of them to // get the most specific sharding. If some of them are not compatible, then // it will just choose the a random sharding among them(say the first one), // with the guarantee that the defaultly chosen sharding will not be from a // ShardBarrierFrom op if there is one within the ShardAs group. HloSharding default_sharding = HloSharding::Replicate(); std::vector<HloSharding> shardings; for (HloInstruction* instruction : shard_as_group) { if (instruction->has_sharding()) { shardings.push_back(instruction->sharding()); if (!instruction->IsCustomCall(spmd::kShardBarrierFrom) && default_sharding.IsReplicated()) { default_sharding = instruction->sharding(); } } } HloSharding common_sharding = hlo_sharding_util::FindCommonSharding(shardings, default_sharding); VLOG(2) << "Aligning shard group: " << shard_as_group_id << " to sharding:" << common_sharding.ToString(); for (HloInstruction* member : shard_as_group) { if (member->IsCustomCall(spmd::kShardBarrierTo)) { continue; } if (provided_shardings.contains(member)) { auto it = unspecified_dims.find(member); if (it != unspecified_dims.end()) { HloSharding partial_replicated = hlo_sharding_util::PartiallyReplicateTiledShardingOnAllDimsExcept( common_sharding, it->second); HloSharding sharding = member->sharding(); if (hlo_sharding_util::MergeShardingIfCompatible( partial_replicated, sharding.NumTiles() + 1, &sharding)) { member->set_sharding(sharding); } } } member->set_sharding(common_sharding); } } // If a ShardBarrierFrom custom-call op is in a shard as group, and relay // the shard as sharding to its original op, do not relay shardings for // ShardbarrierTo op. Then run sharding propagation once more at highest // aggressiveness without propagating shard group. for (HloComputation* computation : module->computations(execution_threads)) { for (HloInstruction* instruction : computation->instructions()) { if (instruction->IsCustomCall(spmd::kShardBarrierFrom) && instruction_to_shard_group_id.contains(instruction) && shard_group_id_to_shard_as_group.contains( instruction_to_shard_group_id.at(instruction))) { HloSharding sharding = instruction->sharding(); hlo_sharding_util::MergeShardingIfCompatible( instruction->mutable_operand(0)->sharding(), sharding.NumTiles(), &sharding); instruction->mutable_operand(0)->set_sharding(std::move(sharding)); } } } TF_RETURN_IF_ERROR( run_to_fix_point(/*aggressiveness=*/3, /*propagate_shard_group=*/false)); // Post-process to remove all "shard-barrier-from" and "shard-barrier-to" // custom-calls. for (HloComputation* computation : module->computations(execution_threads)) { for (HloInstruction* instruction : computation->instructions()) { // If a ShardBarrierFrom custom-call op is in a shard as group, and relay // the shard as sharding to its original op, do not relay shardings for // ShardbarrierTo op. if (instruction->IsCustomCall(spmd::kShardBarrierFrom) && instruction_to_shard_group_id.contains(instruction) && shard_group_id_to_shard_as_group.contains( instruction_to_shard_group_id.at(instruction))) { HloSharding sharding = instruction->sharding(); hlo_sharding_util::MergeShardingIfCompatible( instruction->mutable_operand(0)->sharding(), sharding.NumTiles(), &sharding); instruction->mutable_operand(0)->set_sharding(std::move(sharding)); } if (instruction->IsCustomCall(spmd::kShardBarrierFrom) || instruction->IsCustomCall(spmd::kShardBarrierTo)) { TF_ASSIGN_OR_RETURN(std::ignore, computation->ReplaceInstruction( instruction, instruction->mutable_operand(0), /*preserve_sharding=*/false, /*relay_control_dependency=*/false, /*remove_unused_operands=*/false)); } } } // Post-process for CSE prevention. if (cse_prevention_only_) { for (auto computation : module->computations(execution_threads)) { for (auto instruction : computation->instructions()) { if (!instruction->has_sharding()) { continue; } if (IsCSEPreventionTarget(instruction) && instruction->has_sharding()) { if (!(*original_sharding).contains(instruction)) { // Mark the propagated sharding as for CSE prevention. instruction->set_sharding( SetCSEPreventionSharding(instruction->sharding())); } continue; } auto it = (*original_sharding).find(instruction); if (it != (*original_sharding).end()) { // Revert sharding. instruction->set_sharding(it->second); } else { // Clear sharding. instruction->clear_sharding(); } } } } HloInstruction* root_instruction = module->entry_computation()->root_instruction(); if (saved_root_shardings.size() == allow_spmd_sharding_propagation_to_output_vector_.size() && root_instruction->has_sharding()) { HloSharding root_sharding = root_instruction->sharding(); for (int i = 0; i < saved_root_shardings.size(); ++i) { if (!allow_spmd_sharding_propagation_to_output_vector_[i] && !saved_root_shardings[i].IsUnknown()) { root_sharding.tuple_elements()[i] = saved_root_shardings[i]; } } root_instruction->set_sharding(std::move(root_sharding)); } auto params = module->entry_computation()->parameter_instructions(); if (allow_spmd_sharding_propagation_to_parameters_) { if (allow_spmd_sharding_propagation_to_parameters_vector_.size() == params.size()) { for (int64_t i = 0; i < params.size(); ++i) { if (!allow_spmd_sharding_propagation_to_parameters_vector_[i]) { if (saved_parameter_shardings.contains(i) && !saved_parameter_shardings.at(i).IsUnknown()) { params[i]->set_sharding(saved_parameter_shardings.at(i)); } else { params[i]->clear_sharding(); } } } } else if (params.size() == 1 && saved_parameter_shardings.size() == 1 && params[0]->shape().IsTuple() && params[0]->shape().tuple_shapes_size() == allow_spmd_sharding_propagation_to_parameters_vector_ .size()) { // There is a single parameter which is a tuple with many elements. HloSharding param_sharding = params[0]->sharding(); for (int64_t i = 0; i < params[0]->shape().tuple_shapes_size(); ++i) { HloSharding saved_subsharding = saved_parameter_shardings.at(0).GetSubSharding(params[0]->shape(), {i}); if (!allow_spmd_sharding_propagation_to_parameters_vector_[i] && !saved_subsharding.IsUnknown()) { param_sharding.tuple_elements()[i] = saved_subsharding; } } params[0]->set_sharding(std::move(param_sharding)); } } // Replicate the parameter/output sharding if the propagated sharding does not // evenly partition the parameter/output. std::function<bool(const Shape&, const HloSharding&)> evenly_partitions = [&evenly_partitions](const Shape& shape, const HloSharding& sharding) -> bool { if (!sharding.IsTiled()) { return true; } if (sharding.IsTileMaximal()) { return sharding.IsReplicated(); } if (sharding.IsTuple()) { for (int64_t i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { if (!evenly_partitions(ShapeUtil::GetTupleElementShape(shape, i), sharding.GetSubSharding(shape, {i}))) { return false; } } } for (int64_t i = 0; i < shape.dimensions_size(); ++i) { if (shape.dimensions(i) % sharding.tile_assignment().dim(i) != 0) { return false; } } return true; }; if (allow_spmd_sharding_propagation_to_output_ && root_instruction->has_sharding()) { if (root_instruction->shape().IsTuple() && allow_spmd_sharding_propagation_to_output_vector_.size() == root_instruction->shape().tuple_shapes_size()) { // The output shape is a tuple and sharding propagation is allowed for at // least one of its elements. HloSharding root_sharding = root_instruction->sharding(); for (int64_t i = 0; i < root_instruction->shape().tuple_shapes_size(); ++i) { if (allow_spmd_sharding_propagation_to_output_vector_[i] && !evenly_partitions(root_instruction->shape().tuple_shapes(i), root_sharding.tuple_elements()[i])) { root_sharding.tuple_elements()[i] = HloSharding::Replicate(); } } root_instruction->set_sharding(std::move(root_sharding)); } else if (!root_instruction->shape().IsTuple()) { // The output shape is not tuple and sharding propagation is allowed. if (!evenly_partitions(root_instruction->shape(), root_instruction->sharding())) { root_instruction->set_sharding(HloSharding::Replicate()); } } } if (allow_spmd_sharding_propagation_to_parameters_) { // Sharding propagation is allowed for at least one parameter. if (allow_spmd_sharding_propagation_to_parameters_vector_.size() == params.size()) { for (int64_t i = 0; i < params.size(); ++i) { if (params[i]->has_sharding() && allow_spmd_sharding_propagation_to_parameters_vector_[i] && !evenly_partitions(params[i]->shape(), params[i]->sharding())) { params[i]->set_sharding(HloSharding::Replicate()); } } } else if (params.size() == 1 && params[0]->shape().IsTuple() && params[0]->has_sharding() && params[0]->shape().tuple_shapes_size() == allow_spmd_sharding_propagation_to_parameters_vector_ .size()) { HloSharding param_sharding = params[0]->sharding(); for (int64_t i = 0; i < params[0]->shape().tuple_shapes_size(); ++i) { if (allow_spmd_sharding_propagation_to_parameters_vector_[i] && !evenly_partitions( ShapeUtil::GetSubshapeOneIndex(params[0]->shape(), i), params[0]->sharding().GetSubSharding(params[0]->shape(), {i}))) { param_sharding.tuple_elements()[i] = HloSharding::Replicate(); } } params[0]->set_sharding(std::move(param_sharding)); } } TF_RETURN_IF_ERROR( hlo_sharding_util::CanonicalizeLayoutAfterShardingPropagation( module, allow_spmd_sharding_propagation_to_output_, allow_spmd_sharding_propagation_to_parameters_)); VLOG(1) << "Sharding propagation completed after " << iterations << " iterations"; return any_changed; } absl::call_once(did_registration, [] { RegisterCustomCallPartitioner( spmd::kShardBarrierFrom, std::make_unique<spmd::ShardBarrierFromPartitioner>()); RegisterCustomCallPartitioner( spmd::kShardBarrierTo, std::make_unique<spmd::ShardBarrierToPartitioner>()); }); VLOG(5) << "Shard-As group " << shard_group_id << " contains:"; VLOG(5) << " " << instruction->ToString(); VLOG(5) << "Shard-Like group " << shard_group_id << " contains:"; VLOG(5) << " " << instruction->ToString(); auto is_same_sized_tuple = [](HloModule* module, int64_t size) { if (module->entry_computation()->num_parameters() != 1) { return false; } HloInstruction* param = module->entry_computation()->parameter_instruction(0); return param->shape().IsTuple() && size == param->shape().tuple_shapes_size(); }; auto get_related_instructions = [this](HloInstruction* inst) { if (inst->opcode() == HloOpcode::kWhile) { return std::vector<HloInstruction*>{ inst, inst->while_body()->root_instruction(), inst->while_body()->parameter_instruction(0), inst->while_condition()->parameter_instruction(0)}; } else if (inst->opcode() == HloOpcode::kConditional) { const auto& called_computations = inst->called_computations(); std::vector<HloInstruction*> comps; comps.reserve(called_computations.size() + 1); comps.push_back(inst); for (HloComputation* c : called_computations) { comps.push_back(c->root_instruction()); } return comps; } else if (inst->opcode() == HloOpcode::kCustomCall) { if (sharding_helper_ && sharding_helper_->IsCustomCallShardable(inst)) { return sharding_helper_->GetRelatedInstructions(inst); } else { return std::vector<HloInstruction*>{}; } } else if (inst->opcode() == HloOpcode::kCall) { HloComputation* callee = inst->called_computations().front(); return std::vector<HloInstruction*>{inst, callee->root_instruction()}; } else { CHECK(false); } }; [&](HloInstruction* instruction, absl::flat_hash_set<HloInstruction*>* changed) { auto propagate_to_instruction = [&](HloInstruction* search_inst) { auto related_instructions = get_related_instructions(search_inst); if (absl::c_count(related_instructions, instruction)) { for (HloInstruction* inst : related_instructions) { if (!inst->has_sharding() || inst->sharding() != instruction->sharding()) { VLOG(2) << "Add computation sharding: " << inst->name() << " " << instruction->sharding().ToString(); inst->copy_sharding(instruction); changed->insert(inst); maybe_computation_propagation(inst, changed); } } } }; if (instruction->opcode() == HloOpcode::kConditional || instruction->opcode() == HloOpcode::kWhile || instruction->opcode() == HloOpcode::kCustomCall || instruction->opcode() == HloOpcode::kCall) { propagate_to_instruction(instruction); } if (instruction->opcode() == HloOpcode::kParameter || instruction->parent()->root_instruction() == instruction) { auto it = computation_map.find(instruction->parent()); if (it != computation_map.end()) { propagate_to_instruction(it->second); } } }; auto propagate_to_instruction = [&](HloInstruction* search_inst) { auto related_instructions = get_related_instructions(search_inst); if (absl::c_count(related_instructions, instruction)) { for (HloInstruction* inst : related_instructions) { if (!inst->has_sharding() || inst->sharding() != instruction->sharding()) { VLOG(2) << "Add computation sharding: " << inst->name() << " " << instruction->sharding().ToString(); inst->copy_sharding(instruction); changed->insert(inst); maybe_computation_propagation(inst, changed); } } } }; VLOG(2) << "Add computation sharding: " << inst->name() auto run_to_fix_point = [&](int64_t aggressiveness, bool propagate_shard_group) { absl::flat_hash_set<const HloInstruction*> already_inferred_from_shard_group; absl::flat_hash_set<const HloInstruction*> already_inferred_from_operands; absl::flat_hash_set<const HloInstruction*> already_inferred_from_users; bool changed_last_iter = true; const bool may_merge_partial = is_spmd_ && aggressiveness > 0; while (changed_last_iter) { changed_last_iter = false; int64_t inferred_from_shard_group_counter = 0; int64_t inferred_from_operand_counter = 0; int64_t inferred_from_user_counter = 0; int64_t instruction_counter = 0; int64_t already_sharded_counter = 0; for (const HloComputation* computation : module->computations(execution_threads)) { VLOG(2) << "Consider computation: " << computation->name(); std::vector<HloInstruction*> instructions = computation->MakeInstructionPostOrder(); instruction_counter += instructions.size(); already_sharded_counter += absl::c_count_if( instructions, [](const HloInstruction* inst) { return inst->has_sharding(); }); auto clear_cache = [&](HloInstruction* hlo, HloInstruction* hlo_for_users = nullptr) { for (auto operand : hlo->operands()) { already_inferred_from_users.erase(operand); } if (hlo_for_users == nullptr) { hlo_for_users = hlo; } for (auto user : hlo_for_users->users()) { already_inferred_from_operands.erase(user); // If the user has called computations, then the parameter // instructions of these called computations are also removed from // already_inferred_from_operands. for (auto c : user->called_computations()) { for (auto parameter : c->parameter_instructions()) { already_inferred_from_operands.erase(parameter); } } } if (instruction_to_shard_group_id.contains(hlo)) { const int64_t shard_group_id = instruction_to_shard_group_id.at(hlo); const absl::flat_hash_set<HloInstruction*>& shard_group = shard_group_id_to_shard_as_group.contains(shard_group_id) ? shard_group_id_to_shard_as_group.at(shard_group_id) : shard_group_id_to_shard_like_group.at(shard_group_id); for (HloInstruction* member : shard_group) { if (member != hlo) { already_inferred_from_shard_group.erase(member); } } } }; // 1. Iterate the shard groups to take shardings from instructions of // the same group. if (propagate_shard_group) { for (HloInstruction* instruction : instructions) { if (already_inferred_from_shard_group.contains(instruction)) { continue; } if (!instruction_to_shard_group_id.contains(instruction)) { continue; } const int64_t shard_group_id = instruction_to_shard_group_id.at(instruction); const absl::flat_hash_set<HloInstruction*>& shard_group = shard_group_id_to_shard_as_group.contains(shard_group_id) ? shard_group_id_to_shard_as_group.at(shard_group_id) : shard_group_id_to_shard_like_group.at(shard_group_id); if (provided_shardings.contains(instruction)) { if (!may_merge_partial) { continue; } auto it = unspecified_dims.find(instruction); if (it != unspecified_dims.end() && InferUnspecifiedDimsFromShardGroup(instruction, it->second, shard_group)) { ++inferred_from_shard_group_counter; VLOG(2) << "Refined partial sharding (shard group): " << instruction->ToString(); clear_cache(instruction); already_inferred_from_shard_group.insert(instruction); changed_last_iter = true; } continue; } already_inferred_from_shard_group.insert(instruction); if (InferShardingFromShardGroup(instruction, computation_map, aggressiveness, shard_group)) { ++inferred_from_shard_group_counter; any_changed = true; VLOG(2) << "Add sharding (shard group): " << instruction->ToString(); absl::flat_hash_set<HloInstruction*> changed_in_comp_prop; maybe_computation_propagation(instruction, &changed_in_comp_prop); clear_cache(instruction); for (auto hlo : changed_in_comp_prop) { clear_cache(hlo); } changed_last_iter = true; } } } // 2. Iterate the HLO graph in post order taking shardings from // operands. for (HloInstruction* instruction : instructions) { if (already_inferred_from_operands.contains(instruction)) { continue; } if (provided_shardings.contains(instruction)) { if (!may_merge_partial) { continue; } auto it = unspecified_dims.find(instruction); HloInstruction* man_conversion_op_after; if (it != unspecified_dims.end() && InferUnspecifiedDimsFromOperand(instruction, it->second, &man_conversion_op_after)) { ++inferred_from_operand_counter; VLOG(2) << "Refined partial sharding (forward-pass): " << instruction->ToString(); clear_cache(instruction, man_conversion_op_after); already_inferred_from_operands.insert(instruction); changed_last_iter = true; } continue; } already_inferred_from_operands.insert(instruction); if (InferShardingFromOperands(instruction, computation_map, aggressiveness, *call_graph, execution_threads)) { ++inferred_from_operand_counter; any_changed = true; VLOG(2) << "Add sharding (forward-pass): " << instruction->ToString(); absl::flat_hash_set<HloInstruction*> changed_in_comp_prop; maybe_computation_propagation(instruction, &changed_in_comp_prop); clear_cache(instruction); for (auto hlo : changed_in_comp_prop) { clear_cache(hlo); } changed_last_iter = true; } } // 3. Iterate the HLO graph in reverse post order taking shardings from // users. for (auto it = instructions.rbegin(); it != instructions.rend(); ++it) { if ((*it)->IsCustomCall("SPMDFullToShardShape") || (*it)->IsCustomCall("SPMDShardToFullShape")) { // The manual conversion op is processed together with the sharding // op before it. If the conversion op is removed from cache, the // sharding op should also be removed. if (!already_inferred_from_users.contains(*it)) { already_inferred_from_users.erase((*it)->operand(0)); } } if (already_inferred_from_users.contains(*it)) { continue; } if (provided_shardings.contains(*it)) { if (!may_merge_partial) { continue; } auto uit = unspecified_dims.find(*it); HloInstruction* man_conversion_op_after; if (uit != unspecified_dims.end() && InferUnspecifiedDimsFromUsers( *it, uit->second, aggressiveness, is_spmd_, &man_conversion_op_after, *call_graph)) { ++inferred_from_user_counter; VLOG(2) << "Refined partial sharding (backward-pass): " << (*it)->ToString(); clear_cache(*it, man_conversion_op_after); already_inferred_from_users.insert(*it); if (man_conversion_op_after != nullptr) { already_inferred_from_users.insert(man_conversion_op_after); } changed_last_iter = true; } continue; } already_inferred_from_users.insert(*it); if (InferShardingFromUsers(*it, computation_map, aggressiveness, is_spmd_, sharding_helper_.get(), *call_graph)) { ++inferred_from_user_counter; any_changed = true; VLOG(2) << "Add sharding (backward-pass): " << (*it)->ToString(); absl::flat_hash_set<HloInstruction*> changed_in_comp_prop; maybe_computation_propagation(*it, &changed_in_comp_prop); clear_cache(*it); for (auto hlo : changed_in_comp_prop) { clear_cache(hlo); } changed_last_iter = true; } } } VLOG(1) << "Sharding propagation iteration " << iterations << ";" << "\n total instructions: " << instruction_counter << "\n instructions already sharded: " << already_sharded_counter << "\n shardings inferred from shard group: " << inferred_from_shard_group_counter << "\n shardings inferred from operands: " << inferred_from_operand_counter << "\n shardings inferred from users: " << inferred_from_user_counter << "\n aggressiveness: " << aggressiveness; ++iterations; } return absl::OkStatus(); }; VLOG(2) << "Consider computation: " << computation->name(); auto clear_cache = [&](HloInstruction* hlo, HloInstruction* hlo_for_users = nullptr) { for (auto operand : hlo->operands()) { already_inferred_from_users.erase(operand); } if (hlo_for_users == nullptr) { hlo_for_users = hlo; } for (auto user : hlo_for_users->users()) { already_inferred_from_operands.erase(user); // If the user has called computations, then the parameter // instructions of these called computations are also removed from // already_inferred_from_operands. for (auto c : user->called_computations()) { for (auto parameter : c->parameter_instructions()) { already_inferred_from_operands.erase(parameter); } } } if (instruction_to_shard_group_id.contains(hlo)) { const int64_t shard_group_id = instruction_to_shard_group_id.at(hlo); const absl::flat_hash_set<HloInstruction*>& shard_group = shard_group_id_to_shard_as_group.contains(shard_group_id) ? shard_group_id_to_shard_as_group.at(shard_group_id) : shard_group_id_to_shard_like_group.at(shard_group_id); for (HloInstruction* member : shard_group) { if (member != hlo) { already_inferred_from_shard_group.erase(member); } } } }; VLOG(2) << "Refined partial sharding (shard group): " VLOG(2) << "Add sharding (shard group): " VLOG(2) << "Refined partial sharding (forward-pass): " VLOG(2) << "Add sharding (forward-pass): " VLOG(2) << "Refined partial sharding (backward-pass): " VLOG(2) << "Add sharding (backward-pass): " << (*it)->ToString(); VLOG(1) << "Sharding propagation iteration " << iterations << ";" VLOG(2) << "Aligning shard group: " << shard_as_group_id [&evenly_partitions](const Shape& shape, const HloSharding& sharding) -> bool { if (!sharding.IsTiled()) { return true; } if (sharding.IsTileMaximal()) { return sharding.IsReplicated(); } if (sharding.IsTuple()) { for (int64_t i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { if (!evenly_partitions(ShapeUtil::GetTupleElementShape(shape, i), sharding.GetSubSharding(shape, {i}))) { return false; } } } for (int64_t i = 0; i < shape.dimensions_size(); ++i) { if (shape.dimensions(i) % sharding.tile_assignment().dim(i) != 0) { return false; } } return true; }; VLOG(1) << "Sharding propagation completed after " << iterations
#include "xla/service/sharding_propagation.h" #include <ostream> #include <string> #include <utility> #include <vector> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/log/check.h" #include "absl/log/log.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/ir/hlo_op_metadata.h" #include "xla/hlo/ir/hlo_sharding.h" #include "xla/hlo/transforms/hlo_constant_splitter.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/protobuf_util.h" #include "xla/service/hlo_dce.h" #include "xla/service/hlo_parser.h" #include "xla/tests/hlo_test_base.h" #include "xla/util.h" #include "xla/xla_data.pb.h" #include "tsl/platform/statusor.h" TEST_F(ShardingPropagationTest, ShardAsWithShardBarrier2) { const char* const hlo_string = R"( HloModule module ENTRY %elementwise { %param0 = f32[5,7,11,13]{3,2,1,0} parameter(0) %custom-call.0 = f32[5,7,11,13]{3,2,1,0} custom-call(param0), custom_call_target="Sharding", sharding={devices=[2,1,1,1,4]<=[8] last_tile_dim_replicate}, backend_config="unspecified_dims=[1,2,3]" %shard-barrier-from = f32[5,7,11,13]{3,2,1,0} custom-call(%custom-call.0), custom_call_target="ShardBarrierFrom", custom_call_has_side_effect=true %custom-call.2 = f32[5,7,11,13]{3,2,1,0} custom-call(shard-barrier-from), custom_call_target="Sharding", custom_call_has_side_effect=true, sharding={unknown shard_as 1} %param1 = f32[5,7,11,13]{3,2,1,0} parameter(1) %custom-call.1 = f32[5,7,11,13]{3,2,1,0} custom-call(param1), custom_call_target="Sharding", sharding={devices=[1,2,2,1,2]<=[2,4]T(1,0) last_tile_dim_replicate}, backend_config="unspecified_dims=[0]" %custom-call.3 = f32[5,7,11,13]{3,2,1,0} custom-call(custom-call.1), custom_call_target="Sharding", custom_call_has_side_effect=true, sharding={unknown shard_as 1} ROOT %tuple = (f32[5,7,11,13]{3,2,1,0}, f32[5,7,11,13]{3,2,1,0}) tuple(%custom-call.0, %custom-call.3) })"; TF_ASSERT_OK_AND_ASSIGN(auto module, ParseAndReturnVerifiedModule(hlo_string)); TF_ASSERT_OK_AND_ASSIGN( bool changed, ShardingPropagation( /*is_spmd=*/true, /*propagate_metadata=*/true, /*allow_spmd_sharding_propagation_to_output=*/{true}, /*allow_spmd_sharding_propagation_to_parameters=*/{false, false}) .Run(module.get())); EXPECT_TRUE(changed); XLA_VLOG_LINES(1, module->ToString()); EXPECT_THAT( module->entry_computation()->root_instruction(), op::Sharding( "{{devices=[2,2,2,1]<=[8]}, {devices=[1,2,2,1,2]<=[2,4]T(1,0) " "last_tile_dim_replicate}}")); }
StochasticConvertDecomposerTest_DecomposeStochasticConvertBF16ToS8
xla/service/stochastic_convert_decomposer_test.cc
absl::Status DecomposeStochasticConvert(HloComputation* comp, HloInstruction* instruction) { CHECK(instruction->opcode() == HloOpcode::kStochasticConvert) << "requires a stochastic_convert instruction to decompose, but got: " << instruction->opcode(); CHECK(instruction->operand_count() == 2) << "requires 2 operands for stochastic convert, but got: " << instruction->operand_count(); HloInstruction* operand = instruction->mutable_operand(0); HloInstruction* random = instruction->mutable_operand(1); PrimitiveType from_type = operand->shape().element_type(); PrimitiveType random_type = random->shape().element_type(); PrimitiveType to_type = instruction->shape().element_type(); TF_RETURN_IF_ERROR(ShapeInference::InferStochasticConvertShape( operand->shape(), random->shape(), to_type) .status()); VLOG(1) << "Decomposing instruction: " << instruction->ToString(); // For converting floats to integers, the fractional bits of the operands // are placed into an unsigned integer where the bit representing // 2^-1 is put in the most significant bit. This is then // compared (using an unsigned integer comparison) against the unsigned // random value. The fractional part will be rouneded up if the user-given // random value is less than the fractional bits, otherwise it will be // rounded down. if (primitive_util::IsSignedIntegralType(to_type)) { TF_ASSIGN_OR_RETURN(HloInstruction * operand_sign, MakeUnaryHlo(HloOpcode::kSign, operand)); TF_ASSIGN_OR_RETURN(HloInstruction * should_neg, MakeCompareHlo(Comparison::Direction::kLt, operand_sign, MakeScalarLike(operand_sign, 0))); TF_ASSIGN_OR_RETURN(HloInstruction * operand_abs, MakeUnaryHlo(HloOpcode::kAbs, operand)); TF_ASSIGN_OR_RETURN(HloInstruction * truncated_fp, MakeUnaryHlo(HloOpcode::kFloor, operand_abs)); TF_ASSIGN_OR_RETURN( HloInstruction * fractional, MakeBinaryHlo(HloOpcode::kSubtract, operand_abs, truncated_fp)); // Upcasts the operand to F32 as calculating fixed_fractional needs a // multiplier of 2^16 which can't be represented in F16(whose max // value is 2^16 - 2^5). if (from_type == F16) { fractional = MakeConvertToHlo(fractional, F32); } // Compares fractional values against unsigned random values by // normalizing random values into [0, 1): fractional vs. (random / // random_max). This equals to comparing (fractional * random_max) vs. // random. TF_ASSIGN_OR_RETURN( HloInstruction * fixed_fractional, MakeBinaryHlo( HloOpcode::kMultiply, fractional, MakeScalarLike(fractional, IPow<double>(2, primitive_util::BitWidth( random_type))))); // Rounds the integer output up if the fractional pieces is larger than // the input random number. TF_ASSIGN_OR_RETURN( HloInstruction * should_round_up, MakeCompareHlo(Comparison::Direction::kLt, random, MakeConvertToHlo(fixed_fractional, random_type))); HloInstruction* truncated_int = MakeConvertToHlo(truncated_fp, to_type); TF_ASSIGN_OR_RETURN( truncated_int, MakeSelectHlo(should_round_up, MakeBinaryHlo(HloOpcode::kAdd, truncated_int, MakeScalarLike(truncated_int, 1)) .value(), truncated_int)); TF_ASSIGN_OR_RETURN( HloInstruction * result, MakeSelectHlo(should_neg, MakeUnaryHlo(HloOpcode::kNegate, truncated_int).value(), truncated_int)); auto to_bits = primitive_util::BitWidth(to_type); // Deals with min values auto min = static_cast<int64_t>( (static_cast<uint64_t>(1) + ~static_cast<uint64_t>(1)) << (to_bits - 1)); TF_ASSIGN_OR_RETURN(HloInstruction * is_min, MakeCompareHlo(Comparison::Direction::kLe, operand, MakeScalarLike(operand, min))); TF_ASSIGN_OR_RETURN( result, MakeSelectHlo(is_min, MakeScalarLike(result, min), result)); // Deals with max values auto max = static_cast<int64_t>((static_cast<uint64_t>(1) << (to_bits - 1)) - 1); TF_ASSIGN_OR_RETURN(HloInstruction * is_max, MakeCompareHlo(Comparison::Direction::kGe, operand, MakeScalarLike(operand, max))); TF_ASSIGN_OR_RETURN( result, MakeSelectHlo(is_max, MakeScalarLike(result, max), result)); TF_RETURN_IF_ERROR(instruction->ReplaceAllUsesWith(result)); TF_RETURN_IF_ERROR(comp->RemoveInstruction(instruction)); return absl::OkStatus(); } // TODO(b/232442915): Add support for converting to floats. return Internal("Unsupported stochastic convert: from %s to %s", PrimitiveType_Name(from_type), PrimitiveType_Name(to_type)); } VLOG(1) << "Decomposing instruction: " << instruction->ToString(); absl::StatusOr<bool> StochasticConvertDecomposer::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { bool changed = false; for (HloComputation* computation : module->MakeNonfusionComputations(execution_threads)) { for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (instruction->opcode() != HloOpcode::kStochasticConvert) { continue; } TF_RETURN_IF_ERROR(DecomposeStochasticConvert(computation, instruction)); changed = true; } } return changed; }
#include "xla/service/stochastic_convert_decomposer.h" #include <string> #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/hlo_parser.h" #include "xla/tests/hlo_test_base.h" TEST_F(StochasticConvertDecomposerTest, DecomposeStochasticConvertBF16ToS8) { const std::string module_str = R"( HloModule module ENTRY entry { %arg_param.1 = bf16[65536]{0} parameter(0) %random_param.2 = u16[65536]{0} parameter(1) ROOT %stochastic-convert.3 = s8[65536]{0} stochastic-convert(bf16[65536]{0} %arg_param.1, u16[65536]{0} %random_param.2) } )"; TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module, ParseAndReturnUnverifiedModule((module_str))); StochasticConvertDecomposer decomposer; TF_ASSERT_OK_AND_ASSIGN(bool changed, decomposer.Run(module.get())); EXPECT_TRUE(changed); EXPECT_THAT(module->entry_computation()->root_instruction(), op::Select(op::Compare(), op::Broadcast(), op::Select(op::Compare(), op::Broadcast(), op::Select(op::Compare(), op::Negate(), op::Select())))); }
StochasticConvertDecomposerTest_DecomposeStochasticConvertF32ToS32
xla/service/stochastic_convert_decomposer_test.cc
absl::Status DecomposeStochasticConvert(HloComputation* comp, HloInstruction* instruction) { CHECK(instruction->opcode() == HloOpcode::kStochasticConvert) << "requires a stochastic_convert instruction to decompose, but got: " << instruction->opcode(); CHECK(instruction->operand_count() == 2) << "requires 2 operands for stochastic convert, but got: " << instruction->operand_count(); HloInstruction* operand = instruction->mutable_operand(0); HloInstruction* random = instruction->mutable_operand(1); PrimitiveType from_type = operand->shape().element_type(); PrimitiveType random_type = random->shape().element_type(); PrimitiveType to_type = instruction->shape().element_type(); TF_RETURN_IF_ERROR(ShapeInference::InferStochasticConvertShape( operand->shape(), random->shape(), to_type) .status()); VLOG(1) << "Decomposing instruction: " << instruction->ToString(); // For converting floats to integers, the fractional bits of the operands // are placed into an unsigned integer where the bit representing // 2^-1 is put in the most significant bit. This is then // compared (using an unsigned integer comparison) against the unsigned // random value. The fractional part will be rouneded up if the user-given // random value is less than the fractional bits, otherwise it will be // rounded down. if (primitive_util::IsSignedIntegralType(to_type)) { TF_ASSIGN_OR_RETURN(HloInstruction * operand_sign, MakeUnaryHlo(HloOpcode::kSign, operand)); TF_ASSIGN_OR_RETURN(HloInstruction * should_neg, MakeCompareHlo(Comparison::Direction::kLt, operand_sign, MakeScalarLike(operand_sign, 0))); TF_ASSIGN_OR_RETURN(HloInstruction * operand_abs, MakeUnaryHlo(HloOpcode::kAbs, operand)); TF_ASSIGN_OR_RETURN(HloInstruction * truncated_fp, MakeUnaryHlo(HloOpcode::kFloor, operand_abs)); TF_ASSIGN_OR_RETURN( HloInstruction * fractional, MakeBinaryHlo(HloOpcode::kSubtract, operand_abs, truncated_fp)); // Upcasts the operand to F32 as calculating fixed_fractional needs a // multiplier of 2^16 which can't be represented in F16(whose max // value is 2^16 - 2^5). if (from_type == F16) { fractional = MakeConvertToHlo(fractional, F32); } // Compares fractional values against unsigned random values by // normalizing random values into [0, 1): fractional vs. (random / // random_max). This equals to comparing (fractional * random_max) vs. // random. TF_ASSIGN_OR_RETURN( HloInstruction * fixed_fractional, MakeBinaryHlo( HloOpcode::kMultiply, fractional, MakeScalarLike(fractional, IPow<double>(2, primitive_util::BitWidth( random_type))))); // Rounds the integer output up if the fractional pieces is larger than // the input random number. TF_ASSIGN_OR_RETURN( HloInstruction * should_round_up, MakeCompareHlo(Comparison::Direction::kLt, random, MakeConvertToHlo(fixed_fractional, random_type))); HloInstruction* truncated_int = MakeConvertToHlo(truncated_fp, to_type); TF_ASSIGN_OR_RETURN( truncated_int, MakeSelectHlo(should_round_up, MakeBinaryHlo(HloOpcode::kAdd, truncated_int, MakeScalarLike(truncated_int, 1)) .value(), truncated_int)); TF_ASSIGN_OR_RETURN( HloInstruction * result, MakeSelectHlo(should_neg, MakeUnaryHlo(HloOpcode::kNegate, truncated_int).value(), truncated_int)); auto to_bits = primitive_util::BitWidth(to_type); // Deals with min values auto min = static_cast<int64_t>( (static_cast<uint64_t>(1) + ~static_cast<uint64_t>(1)) << (to_bits - 1)); TF_ASSIGN_OR_RETURN(HloInstruction * is_min, MakeCompareHlo(Comparison::Direction::kLe, operand, MakeScalarLike(operand, min))); TF_ASSIGN_OR_RETURN( result, MakeSelectHlo(is_min, MakeScalarLike(result, min), result)); // Deals with max values auto max = static_cast<int64_t>((static_cast<uint64_t>(1) << (to_bits - 1)) - 1); TF_ASSIGN_OR_RETURN(HloInstruction * is_max, MakeCompareHlo(Comparison::Direction::kGe, operand, MakeScalarLike(operand, max))); TF_ASSIGN_OR_RETURN( result, MakeSelectHlo(is_max, MakeScalarLike(result, max), result)); TF_RETURN_IF_ERROR(instruction->ReplaceAllUsesWith(result)); TF_RETURN_IF_ERROR(comp->RemoveInstruction(instruction)); return absl::OkStatus(); } // TODO(b/232442915): Add support for converting to floats. return Internal("Unsupported stochastic convert: from %s to %s", PrimitiveType_Name(from_type), PrimitiveType_Name(to_type)); } VLOG(1) << "Decomposing instruction: " << instruction->ToString(); absl::StatusOr<bool> StochasticConvertDecomposer::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { bool changed = false; for (HloComputation* computation : module->MakeNonfusionComputations(execution_threads)) { for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (instruction->opcode() != HloOpcode::kStochasticConvert) { continue; } TF_RETURN_IF_ERROR(DecomposeStochasticConvert(computation, instruction)); changed = true; } } return changed; }
#include "xla/service/stochastic_convert_decomposer.h" #include <string> #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/hlo_parser.h" #include "xla/tests/hlo_test_base.h" TEST_F(StochasticConvertDecomposerTest, DecomposeStochasticConvertF32ToS32) { const std::string module_str = R"( HloModule module ENTRY entry { %arg_param.1 = f32[65536]{0} parameter(0) %random_param.2 = u32[65536]{0} parameter(1) ROOT %stochastic-convert.3 = s32[65536]{0} stochastic-convert(f32[65536]{0} %arg_param.1, u32[65536]{0} %random_param.2) } )"; TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module, ParseAndReturnUnverifiedModule((module_str))); StochasticConvertDecomposer decomposer; TF_ASSERT_OK_AND_ASSIGN(bool changed, decomposer.Run(module.get())); EXPECT_TRUE(changed); EXPECT_THAT(module->entry_computation()->root_instruction(), op::Select(op::Compare(), op::Broadcast(), op::Select(op::Compare(), op::Broadcast(), op::Select(op::Compare(), op::Negate(), op::Select())))); }
StochasticConvertDecomposerTest_WrongRandomBitWidth
xla/service/stochastic_convert_decomposer_test.cc
absl::Status DecomposeStochasticConvert(HloComputation* comp, HloInstruction* instruction) { CHECK(instruction->opcode() == HloOpcode::kStochasticConvert) << "requires a stochastic_convert instruction to decompose, but got: " << instruction->opcode(); CHECK(instruction->operand_count() == 2) << "requires 2 operands for stochastic convert, but got: " << instruction->operand_count(); HloInstruction* operand = instruction->mutable_operand(0); HloInstruction* random = instruction->mutable_operand(1); PrimitiveType from_type = operand->shape().element_type(); PrimitiveType random_type = random->shape().element_type(); PrimitiveType to_type = instruction->shape().element_type(); TF_RETURN_IF_ERROR(ShapeInference::InferStochasticConvertShape( operand->shape(), random->shape(), to_type) .status()); VLOG(1) << "Decomposing instruction: " << instruction->ToString(); // For converting floats to integers, the fractional bits of the operands // are placed into an unsigned integer where the bit representing // 2^-1 is put in the most significant bit. This is then // compared (using an unsigned integer comparison) against the unsigned // random value. The fractional part will be rouneded up if the user-given // random value is less than the fractional bits, otherwise it will be // rounded down. if (primitive_util::IsSignedIntegralType(to_type)) { TF_ASSIGN_OR_RETURN(HloInstruction * operand_sign, MakeUnaryHlo(HloOpcode::kSign, operand)); TF_ASSIGN_OR_RETURN(HloInstruction * should_neg, MakeCompareHlo(Comparison::Direction::kLt, operand_sign, MakeScalarLike(operand_sign, 0))); TF_ASSIGN_OR_RETURN(HloInstruction * operand_abs, MakeUnaryHlo(HloOpcode::kAbs, operand)); TF_ASSIGN_OR_RETURN(HloInstruction * truncated_fp, MakeUnaryHlo(HloOpcode::kFloor, operand_abs)); TF_ASSIGN_OR_RETURN( HloInstruction * fractional, MakeBinaryHlo(HloOpcode::kSubtract, operand_abs, truncated_fp)); // Upcasts the operand to F32 as calculating fixed_fractional needs a // multiplier of 2^16 which can't be represented in F16(whose max // value is 2^16 - 2^5). if (from_type == F16) { fractional = MakeConvertToHlo(fractional, F32); } // Compares fractional values against unsigned random values by // normalizing random values into [0, 1): fractional vs. (random / // random_max). This equals to comparing (fractional * random_max) vs. // random. TF_ASSIGN_OR_RETURN( HloInstruction * fixed_fractional, MakeBinaryHlo( HloOpcode::kMultiply, fractional, MakeScalarLike(fractional, IPow<double>(2, primitive_util::BitWidth( random_type))))); // Rounds the integer output up if the fractional pieces is larger than // the input random number. TF_ASSIGN_OR_RETURN( HloInstruction * should_round_up, MakeCompareHlo(Comparison::Direction::kLt, random, MakeConvertToHlo(fixed_fractional, random_type))); HloInstruction* truncated_int = MakeConvertToHlo(truncated_fp, to_type); TF_ASSIGN_OR_RETURN( truncated_int, MakeSelectHlo(should_round_up, MakeBinaryHlo(HloOpcode::kAdd, truncated_int, MakeScalarLike(truncated_int, 1)) .value(), truncated_int)); TF_ASSIGN_OR_RETURN( HloInstruction * result, MakeSelectHlo(should_neg, MakeUnaryHlo(HloOpcode::kNegate, truncated_int).value(), truncated_int)); auto to_bits = primitive_util::BitWidth(to_type); // Deals with min values auto min = static_cast<int64_t>( (static_cast<uint64_t>(1) + ~static_cast<uint64_t>(1)) << (to_bits - 1)); TF_ASSIGN_OR_RETURN(HloInstruction * is_min, MakeCompareHlo(Comparison::Direction::kLe, operand, MakeScalarLike(operand, min))); TF_ASSIGN_OR_RETURN( result, MakeSelectHlo(is_min, MakeScalarLike(result, min), result)); // Deals with max values auto max = static_cast<int64_t>((static_cast<uint64_t>(1) << (to_bits - 1)) - 1); TF_ASSIGN_OR_RETURN(HloInstruction * is_max, MakeCompareHlo(Comparison::Direction::kGe, operand, MakeScalarLike(operand, max))); TF_ASSIGN_OR_RETURN( result, MakeSelectHlo(is_max, MakeScalarLike(result, max), result)); TF_RETURN_IF_ERROR(instruction->ReplaceAllUsesWith(result)); TF_RETURN_IF_ERROR(comp->RemoveInstruction(instruction)); return absl::OkStatus(); } // TODO(b/232442915): Add support for converting to floats. return Internal("Unsupported stochastic convert: from %s to %s", PrimitiveType_Name(from_type), PrimitiveType_Name(to_type)); } VLOG(1) << "Decomposing instruction: " << instruction->ToString(); absl::StatusOr<bool> StochasticConvertDecomposer::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { bool changed = false; for (HloComputation* computation : module->MakeNonfusionComputations(execution_threads)) { for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (instruction->opcode() != HloOpcode::kStochasticConvert) { continue; } TF_RETURN_IF_ERROR(DecomposeStochasticConvert(computation, instruction)); changed = true; } } return changed; }
#include "xla/service/stochastic_convert_decomposer.h" #include <string> #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/hlo_parser.h" #include "xla/tests/hlo_test_base.h" TEST_F(StochasticConvertDecomposerTest, WrongRandomBitWidth) { const std::string module_str = R"( HloModule module ENTRY entry { %arg_param.1 = bf16[65536]{0} parameter(0) %random_param.2 = u32[65536]{0} parameter(1) ROOT %stochastic-convert.3 = s32[65536]{0} stochastic-convert(bf16[65536]{0} %arg_param.1, u32[65536]{0} %random_param.2) } )"; TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module, ParseAndReturnUnverifiedModule((module_str))); StochasticConvertDecomposer decomposer; auto result = decomposer.Run(module.get()); EXPECT_NE(absl::OkStatus(), result.status()); EXPECT_THAT(result.status().message(), HasSubstr("have same bits")); }
StochasticConvertDecomposerTest_WrongRandomType
xla/service/stochastic_convert_decomposer_test.cc
absl::Status DecomposeStochasticConvert(HloComputation* comp, HloInstruction* instruction) { CHECK(instruction->opcode() == HloOpcode::kStochasticConvert) << "requires a stochastic_convert instruction to decompose, but got: " << instruction->opcode(); CHECK(instruction->operand_count() == 2) << "requires 2 operands for stochastic convert, but got: " << instruction->operand_count(); HloInstruction* operand = instruction->mutable_operand(0); HloInstruction* random = instruction->mutable_operand(1); PrimitiveType from_type = operand->shape().element_type(); PrimitiveType random_type = random->shape().element_type(); PrimitiveType to_type = instruction->shape().element_type(); TF_RETURN_IF_ERROR(ShapeInference::InferStochasticConvertShape( operand->shape(), random->shape(), to_type) .status()); VLOG(1) << "Decomposing instruction: " << instruction->ToString(); // For converting floats to integers, the fractional bits of the operands // are placed into an unsigned integer where the bit representing // 2^-1 is put in the most significant bit. This is then // compared (using an unsigned integer comparison) against the unsigned // random value. The fractional part will be rouneded up if the user-given // random value is less than the fractional bits, otherwise it will be // rounded down. if (primitive_util::IsSignedIntegralType(to_type)) { TF_ASSIGN_OR_RETURN(HloInstruction * operand_sign, MakeUnaryHlo(HloOpcode::kSign, operand)); TF_ASSIGN_OR_RETURN(HloInstruction * should_neg, MakeCompareHlo(Comparison::Direction::kLt, operand_sign, MakeScalarLike(operand_sign, 0))); TF_ASSIGN_OR_RETURN(HloInstruction * operand_abs, MakeUnaryHlo(HloOpcode::kAbs, operand)); TF_ASSIGN_OR_RETURN(HloInstruction * truncated_fp, MakeUnaryHlo(HloOpcode::kFloor, operand_abs)); TF_ASSIGN_OR_RETURN( HloInstruction * fractional, MakeBinaryHlo(HloOpcode::kSubtract, operand_abs, truncated_fp)); // Upcasts the operand to F32 as calculating fixed_fractional needs a // multiplier of 2^16 which can't be represented in F16(whose max // value is 2^16 - 2^5). if (from_type == F16) { fractional = MakeConvertToHlo(fractional, F32); } // Compares fractional values against unsigned random values by // normalizing random values into [0, 1): fractional vs. (random / // random_max). This equals to comparing (fractional * random_max) vs. // random. TF_ASSIGN_OR_RETURN( HloInstruction * fixed_fractional, MakeBinaryHlo( HloOpcode::kMultiply, fractional, MakeScalarLike(fractional, IPow<double>(2, primitive_util::BitWidth( random_type))))); // Rounds the integer output up if the fractional pieces is larger than // the input random number. TF_ASSIGN_OR_RETURN( HloInstruction * should_round_up, MakeCompareHlo(Comparison::Direction::kLt, random, MakeConvertToHlo(fixed_fractional, random_type))); HloInstruction* truncated_int = MakeConvertToHlo(truncated_fp, to_type); TF_ASSIGN_OR_RETURN( truncated_int, MakeSelectHlo(should_round_up, MakeBinaryHlo(HloOpcode::kAdd, truncated_int, MakeScalarLike(truncated_int, 1)) .value(), truncated_int)); TF_ASSIGN_OR_RETURN( HloInstruction * result, MakeSelectHlo(should_neg, MakeUnaryHlo(HloOpcode::kNegate, truncated_int).value(), truncated_int)); auto to_bits = primitive_util::BitWidth(to_type); // Deals with min values auto min = static_cast<int64_t>( (static_cast<uint64_t>(1) + ~static_cast<uint64_t>(1)) << (to_bits - 1)); TF_ASSIGN_OR_RETURN(HloInstruction * is_min, MakeCompareHlo(Comparison::Direction::kLe, operand, MakeScalarLike(operand, min))); TF_ASSIGN_OR_RETURN( result, MakeSelectHlo(is_min, MakeScalarLike(result, min), result)); // Deals with max values auto max = static_cast<int64_t>((static_cast<uint64_t>(1) << (to_bits - 1)) - 1); TF_ASSIGN_OR_RETURN(HloInstruction * is_max, MakeCompareHlo(Comparison::Direction::kGe, operand, MakeScalarLike(operand, max))); TF_ASSIGN_OR_RETURN( result, MakeSelectHlo(is_max, MakeScalarLike(result, max), result)); TF_RETURN_IF_ERROR(instruction->ReplaceAllUsesWith(result)); TF_RETURN_IF_ERROR(comp->RemoveInstruction(instruction)); return absl::OkStatus(); } // TODO(b/232442915): Add support for converting to floats. return Internal("Unsupported stochastic convert: from %s to %s", PrimitiveType_Name(from_type), PrimitiveType_Name(to_type)); } VLOG(1) << "Decomposing instruction: " << instruction->ToString(); absl::StatusOr<bool> StochasticConvertDecomposer::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { bool changed = false; for (HloComputation* computation : module->MakeNonfusionComputations(execution_threads)) { for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (instruction->opcode() != HloOpcode::kStochasticConvert) { continue; } TF_RETURN_IF_ERROR(DecomposeStochasticConvert(computation, instruction)); changed = true; } } return changed; }
#include "xla/service/stochastic_convert_decomposer.h" #include <string> #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/hlo_parser.h" #include "xla/tests/hlo_test_base.h" TEST_F(StochasticConvertDecomposerTest, WrongRandomType) { const std::string module_str = R"( HloModule module ENTRY entry { %arg_param.1 = f32[65536]{0} parameter(0) %random_param.2 = s32[65536]{0} parameter(1) ROOT %stochastic-convert.3 = s32[65536]{0} stochastic-convert(f32[65536]{0} %arg_param.1, s32[65536]{0} %random_param.2) } )"; TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module, ParseAndReturnUnverifiedModule((module_str))); StochasticConvertDecomposer decomposer; auto result = decomposer.Run(module.get()); EXPECT_NE(absl::OkStatus(), result.status()); EXPECT_THAT(result.status().message(), HasSubstr("must be unsigned integers")); }
TripCountAnnotatorTest_Int64Overflow
xla/service/while_loop_trip_count_annotator_test.cc
absl::StatusOr<bool> WhileLoopTripCountAnnotator::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { bool changed = false; for (const HloComputation* comp : module->computations(execution_threads)) { for (HloInstruction* instr : comp->instructions()) { if (instr->opcode() != HloOpcode::kWhile) { continue; } if (auto trip_count = ComputeWhileLoopTripCount(instr)) { WhileLoopBackendConfig config; config.mutable_known_trip_count()->set_n(*trip_count); TF_RETURN_IF_ERROR(instr->set_backend_config(config)); changed = true; } } } return changed; }
#include "xla/service/while_loop_trip_count_annotator.h" #include "xla/test.h" #include "xla/tests/hlo_test_base.h" #include "xla/xla_data.pb.h" #include "tsl/platform/statusor.h" class TripCountAnnotatorTest : public HloTestBase {}; TEST_F(TripCountAnnotatorTest, Int64Overflow) { // for(i = INT64_MIN; i < INT64_MAX; ++i) // // We store the trip count as an int64_t, so this loop is unanalyzable. const char* kModuleStr = R"( HloModule test Body { param = (s64[]) parameter(0) i = s64[] get-tuple-element(param), index=0 one = s64[] constant(1) i_plus_one = s64[] add(i, one) ROOT tuple = (s64[]) tuple(i_plus_one) } Cond { param = (s64[]) parameter(0) i = s64[] get-tuple-element(param), index=0 trip_count = s64[] constant(9223372036854775807) // 2^63-1 ROOT done = pred[] compare(i, trip_count), direction=LE } ENTRY test { i_start = s64[] constant(-9223372036854775808) // -2^63 initial_tuple = (s64[]) tuple(i_start) ROOT while = (s64[]) while(initial_tuple), condition=Cond, body=Body })"; TF_ASSERT_OK_AND_ASSIGN(auto m, ParseAndReturnVerifiedModule(kModuleStr)); WhileLoopTripCountAnnotator pass; TF_ASSERT_OK_AND_ASSIGN(bool changed, RunHloPass(&pass, m.get())); EXPECT_FALSE(changed); }
TripCountAnnotatorTest_KnownLargeTripCount
xla/service/while_loop_trip_count_annotator_test.cc
absl::StatusOr<bool> WhileLoopTripCountAnnotator::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { bool changed = false; for (const HloComputation* comp : module->computations(execution_threads)) { for (HloInstruction* instr : comp->instructions()) { if (instr->opcode() != HloOpcode::kWhile) { continue; } if (auto trip_count = ComputeWhileLoopTripCount(instr)) { WhileLoopBackendConfig config; config.mutable_known_trip_count()->set_n(*trip_count); TF_RETURN_IF_ERROR(instr->set_backend_config(config)); changed = true; } } } return changed; }
#include "xla/service/while_loop_trip_count_annotator.h" #include "xla/test.h" #include "xla/tests/hlo_test_base.h" #include "xla/xla_data.pb.h" #include "tsl/platform/statusor.h" class TripCountAnnotatorTest : public HloTestBase {}; TEST_F(TripCountAnnotatorTest, KnownLargeTripCount) { const char* kModuleStr = R"( HloModule test Body { param = (s32[]) parameter(0) i = s32[] get-tuple-element(param), index=0 one = s32[] constant(1) i_plus_one = s32[] add(i, one) ROOT tuple = (s32[]) tuple(i_plus_one) } Cond { param = (s32[]) parameter(0) i = s32[] get-tuple-element(param), index=0 trip_count = s32[] constant(1000000) ROOT done = pred[] compare(i, trip_count), direction=LT } ENTRY test { i_start = s32[] constant(0) initial_tuple = (s32[]) tuple(i_start) ROOT while = (s32[]) while(initial_tuple), condition=Cond, body=Body })"; TF_ASSERT_OK_AND_ASSIGN(auto m, ParseAndReturnVerifiedModule(kModuleStr)); WhileLoopTripCountAnnotator pass; TF_ASSERT_OK_AND_ASSIGN(bool changed, RunHloPass(&pass, m.get())); ASSERT_TRUE(changed); TF_ASSERT_OK_AND_ASSIGN(auto config, m->entry_computation() ->root_instruction() ->backend_config<WhileLoopBackendConfig>()); EXPECT_EQ(1000000, config.known_trip_count().n()); }
TripCountAnnotatorTest_KnownSmallTripCount
xla/service/while_loop_trip_count_annotator_test.cc
absl::StatusOr<bool> WhileLoopTripCountAnnotator::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { bool changed = false; for (const HloComputation* comp : module->computations(execution_threads)) { for (HloInstruction* instr : comp->instructions()) { if (instr->opcode() != HloOpcode::kWhile) { continue; } if (auto trip_count = ComputeWhileLoopTripCount(instr)) { WhileLoopBackendConfig config; config.mutable_known_trip_count()->set_n(*trip_count); TF_RETURN_IF_ERROR(instr->set_backend_config(config)); changed = true; } } } return changed; }
#include "xla/service/while_loop_trip_count_annotator.h" #include "xla/test.h" #include "xla/tests/hlo_test_base.h" #include "xla/xla_data.pb.h" #include "tsl/platform/statusor.h" class TripCountAnnotatorTest : public HloTestBase {}; TEST_F(TripCountAnnotatorTest, KnownSmallTripCount) { const char* kModuleStr = R"( HloModule test Body { param = (s32[]) parameter(0) i = s32[] get-tuple-element(param), index=0 one = s32[] constant(1) i_plus_one = s32[] add(i, one) ROOT tuple = (s32[]) tuple(i_plus_one) } Cond { param = (s32[]) parameter(0) i = s32[] get-tuple-element(param), index=0 trip_count = s32[] constant(10) ROOT done = pred[] compare(i, trip_count), direction=LT } ENTRY test { i_start = s32[] constant(0) initial_tuple = (s32[]) tuple(i_start) ROOT while = (s32[]) while(initial_tuple), condition=Cond, body=Body })"; TF_ASSERT_OK_AND_ASSIGN(auto m, ParseAndReturnVerifiedModule(kModuleStr)); WhileLoopTripCountAnnotator pass; TF_ASSERT_OK_AND_ASSIGN(bool changed, RunHloPass(&pass, m.get())); ASSERT_TRUE(changed); TF_ASSERT_OK_AND_ASSIGN(auto config, m->entry_computation() ->root_instruction() ->backend_config<WhileLoopBackendConfig>()); EXPECT_EQ(10, config.known_trip_count().n()); }
TripCountAnnotatorTest_LessThanOrEqualTo
xla/service/while_loop_trip_count_annotator_test.cc
absl::StatusOr<bool> WhileLoopTripCountAnnotator::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { bool changed = false; for (const HloComputation* comp : module->computations(execution_threads)) { for (HloInstruction* instr : comp->instructions()) { if (instr->opcode() != HloOpcode::kWhile) { continue; } if (auto trip_count = ComputeWhileLoopTripCount(instr)) { WhileLoopBackendConfig config; config.mutable_known_trip_count()->set_n(*trip_count); TF_RETURN_IF_ERROR(instr->set_backend_config(config)); changed = true; } } } return changed; }
#include "xla/service/while_loop_trip_count_annotator.h" #include "xla/test.h" #include "xla/tests/hlo_test_base.h" #include "xla/xla_data.pb.h" #include "tsl/platform/statusor.h" class TripCountAnnotatorTest : public HloTestBase {}; TEST_F(TripCountAnnotatorTest, LessThanOrEqualTo) { const char* kModuleStr = R"( HloModule test Body { param = (s32[]) parameter(0) i = s32[] get-tuple-element(param), index=0 one = s32[] constant(1) i_plus_one = s32[] add(i, one) ROOT tuple = (s32[]) tuple(i_plus_one) } Cond { param = (s32[]) parameter(0) i = s32[] get-tuple-element(param), index=0 trip_count = s32[] constant(1000000) ROOT done = pred[] compare(i, trip_count), direction=LE } ENTRY test { i_start = s32[] constant(10) initial_tuple = (s32[]) tuple(i_start) ROOT while = (s32[]) while(initial_tuple), condition=Cond, body=Body })"; TF_ASSERT_OK_AND_ASSIGN(auto m, ParseAndReturnVerifiedModule(kModuleStr)); WhileLoopTripCountAnnotator pass; TF_ASSERT_OK_AND_ASSIGN(bool changed, RunHloPass(&pass, m.get())); ASSERT_TRUE(changed); TF_ASSERT_OK_AND_ASSIGN(auto config, m->entry_computation() ->root_instruction() ->backend_config<WhileLoopBackendConfig>()); EXPECT_EQ(999991, config.known_trip_count().n()); }
TripCountAnnotatorTest_NonzeroStart
xla/service/while_loop_trip_count_annotator_test.cc
absl::StatusOr<bool> WhileLoopTripCountAnnotator::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { bool changed = false; for (const HloComputation* comp : module->computations(execution_threads)) { for (HloInstruction* instr : comp->instructions()) { if (instr->opcode() != HloOpcode::kWhile) { continue; } if (auto trip_count = ComputeWhileLoopTripCount(instr)) { WhileLoopBackendConfig config; config.mutable_known_trip_count()->set_n(*trip_count); TF_RETURN_IF_ERROR(instr->set_backend_config(config)); changed = true; } } } return changed; }
#include "xla/service/while_loop_trip_count_annotator.h" #include "xla/test.h" #include "xla/tests/hlo_test_base.h" #include "xla/xla_data.pb.h" #include "tsl/platform/statusor.h" class TripCountAnnotatorTest : public HloTestBase {}; TEST_F(TripCountAnnotatorTest, NonzeroStart) { const char* kModuleStr = R"( HloModule test Body { param = (s32[]) parameter(0) i = s32[] get-tuple-element(param), index=0 one = s32[] constant(1) i_plus_one = s32[] add(i, one) ROOT tuple = (s32[]) tuple(i_plus_one) } Cond { param = (s32[]) parameter(0) i = s32[] get-tuple-element(param), index=0 trip_count = s32[] constant(1000000) ROOT done = pred[] compare(i, trip_count), direction=LT } ENTRY test { i_start = s32[] constant(10) initial_tuple = (s32[]) tuple(i_start) ROOT while = (s32[]) while(initial_tuple), condition=Cond, body=Body })"; TF_ASSERT_OK_AND_ASSIGN(auto m, ParseAndReturnVerifiedModule(kModuleStr)); WhileLoopTripCountAnnotator pass; TF_ASSERT_OK_AND_ASSIGN(bool changed, RunHloPass(&pass, m.get())); ASSERT_TRUE(changed); TF_ASSERT_OK_AND_ASSIGN(auto config, m->entry_computation() ->root_instruction() ->backend_config<WhileLoopBackendConfig>()); EXPECT_EQ(999990, config.known_trip_count().n()); }
TupleSimplifierTest_CanExcludeEntryComputation
xla/service/tuple_simplifier_test.cc
TupleSimplifier::TupleSimplifier(bool exclude_entry_computation) : exclude_entry_computation_(exclude_entry_computation) {} absl::StatusOr<bool> TupleSimplifier::RemoveWholeTuple(HloInstruction* tuple) { HloInstruction* top_tuple = nullptr; for (int64_t operand_number = 0; operand_number < tuple->operand_count(); ++operand_number) { HloInstruction* operand = tuple->mutable_operand(operand_number); if (operand->opcode() != HloOpcode::kGetTupleElement || operand->tuple_index() != operand_number) { return false; } if (top_tuple == nullptr) { top_tuple = operand->mutable_operand(0); if (!ShapeUtil::Compatible(top_tuple->shape(), tuple->shape())) { return false; } } else if (top_tuple != operand->operand(0)) { return false; } } if (top_tuple == nullptr) { return false; } TF_ASSIGN_OR_RETURN(bool changed, tuple->parent()->ReplaceInstruction( tuple, top_tuple, /*preserve_sharding=*/true)); return changed; } absl::StatusOr<bool> TupleSimplifier::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { // Initially add all GTE and Tuple instructions to the worklist. bool changed = false; for (auto* computation : module->computations(execution_threads)) { if (exclude_entry_computation_ && computation == module->entry_computation()) { continue; } for (auto* instruction : computation->MakeInstructionPostOrder()) { if (instruction->opcode() == HloOpcode::kTuple) { TF_ASSIGN_OR_RETURN(bool c, RemoveWholeTuple(instruction)); changed |= c; } else { auto ancestor = instruction->LatestNonGteAncestorAndIndex(); if (ancestor.first == instruction) { continue; } // If possible replace a chain of GTE with the operation which produces // the element. For example, replace uses of GTE with below with just // 'Op' (assuming 'Op' is at the index of the GTE instruction): // // ... Op ... // \ | / // Tuple // | // GTE // ... // | // GTE // | // GTE // // Note that this deletes the Tuple instruction altogether. In addition, // if only a subset of tuple's elements are used, this transform // optimizes them one at a time, and after the last use is optimized, // the Tuple will also be deleted. HloInstruction* replacement = ancestor.first; for (int i = 0; i < ancestor.second.size(); ++i) { if (replacement->opcode() != HloOpcode::kTuple) { replacement = nullptr; break; } replacement = replacement->mutable_operand(ancestor.second[i]); } if (replacement) { TF_ASSIGN_OR_RETURN(bool replaced, computation->ReplaceInstruction( instruction, replacement, /*preserve_sharding=*/true, /*relay_control_dependency=*/true)); changed |= replaced; } } } } return changed; }
#include "xla/service/tuple_simplifier.h" #include <memory> #include <utility> #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/literal.h" #include "xla/shape_util.h" #include "xla/test.h" #include "xla/tests/hlo_test_base.h" #include "xla/types.h" #include "tsl/lib/core/status_test_util.h" class TupleSimplifierTest : public HloTestBase { protected: void Run(HloModule* module, bool change_expected) { auto changed_status = RunHloPass(TupleSimplifier(), module); TF_ASSERT_OK(changed_status.status()); EXPECT_EQ(change_expected, changed_status.value()); } void Run(HloModule* module, bool change_expected, bool exclude_entry) { auto changed_status = RunHloPass(TupleSimplifier(exclude_entry), module); TF_ASSERT_OK(changed_status.status()); EXPECT_EQ(change_expected, changed_status.value()); } const Shape scalar_shape_ = ShapeUtil::MakeShape(F32, {}); const Shape tuple_shape_ = ShapeUtil::MakeTupleShape( {ShapeUtil::MakeShape(F32, {}), ShapeUtil::MakeShape(F32, {}), ShapeUtil::MakeShape(F32, {})}); }; TEST_F(TupleSimplifierTest, CanExcludeEntryComputation) { // Verify that the root computation can be excluded auto module = CreateNewVerifiedModule(); HloInstruction* p0; HloInstruction* p1; HloComputation* c0; HloComputation* c1; HloComputation* entry; { HloComputation::Builder builder(TestName() + "_1"); p0 = builder.AddInstruction( HloInstruction::CreateParameter(0, tuple_shape_, "param")); HloInstruction* gte0 = builder.AddInstruction( HloInstruction::CreateGetTupleElement(scalar_shape_, p0, 0)); HloInstruction* gte1 = builder.AddInstruction( HloInstruction::CreateGetTupleElement(scalar_shape_, p0, 1)); HloInstruction* gte2 = builder.AddInstruction( HloInstruction::CreateGetTupleElement(scalar_shape_, p0, 2)); builder.AddInstruction(HloInstruction::CreateTuple({gte0, gte1, gte2})); c0 = module->AddEmbeddedComputation(builder.Build()); } { HloComputation::Builder builder(TestName() + "_2"); p1 = builder.AddInstruction( HloInstruction::CreateParameter(0, tuple_shape_, "param")); HloInstruction* gte0 = builder.AddInstruction( HloInstruction::CreateGetTupleElement(scalar_shape_, p1, 0)); HloInstruction* gte1 = builder.AddInstruction( HloInstruction::CreateGetTupleElement(scalar_shape_, p1, 1)); HloInstruction* gte2 = builder.AddInstruction( HloInstruction::CreateGetTupleElement(scalar_shape_, p1, 2)); builder.AddInstruction(HloInstruction::CreateTuple({gte0, gte1, gte2})); c1 = module->AddEmbeddedComputation(builder.Build()); } { HloComputation::Builder builder(TestName() + "_Entry"); HloInstruction* tuple_param = builder.AddInstruction( HloInstruction::CreateParameter(0, tuple_shape_, "param")); HloInstruction* call0 = builder.AddInstruction( HloInstruction::CreateCall(tuple_shape_, {tuple_param}, c0)); HloInstruction* call1 = builder.AddInstruction( HloInstruction::CreateCall(tuple_shape_, {tuple_param}, c1)); HloInstruction* gte0 = builder.AddInstruction( HloInstruction::CreateGetTupleElement(scalar_shape_, call0, 0)); HloInstruction* gte1 = builder.AddInstruction( HloInstruction::CreateGetTupleElement(scalar_shape_, call1, 1)); HloInstruction* tuple0 = builder.AddInstruction(HloInstruction::CreateTuple({gte0, gte1})); HloInstruction* gte2 = builder.AddInstruction( HloInstruction::CreateGetTupleElement(scalar_shape_, tuple0, 0)); HloInstruction* gte3 = builder.AddInstruction( HloInstruction::CreateGetTupleElement(scalar_shape_, tuple0, 1)); builder.AddInstruction(HloInstruction::CreateTuple({gte2, gte3})); entry = module->AddEntryComputation(builder.Build()); } Run(module.get(), /*change_expected=*/true, /*exclude_entry=*/true); EXPECT_THAT(c0->root_instruction(), p0); EXPECT_THAT(c1->root_instruction(), p1); EXPECT_THAT(entry->instruction_count(), 9); }
TupleSimplifierTest_GteOfTuple
xla/service/tuple_simplifier_test.cc
TupleSimplifier::TupleSimplifier(bool exclude_entry_computation) : exclude_entry_computation_(exclude_entry_computation) {} absl::StatusOr<bool> TupleSimplifier::RemoveWholeTuple(HloInstruction* tuple) { HloInstruction* top_tuple = nullptr; for (int64_t operand_number = 0; operand_number < tuple->operand_count(); ++operand_number) { HloInstruction* operand = tuple->mutable_operand(operand_number); if (operand->opcode() != HloOpcode::kGetTupleElement || operand->tuple_index() != operand_number) { return false; } if (top_tuple == nullptr) { top_tuple = operand->mutable_operand(0); if (!ShapeUtil::Compatible(top_tuple->shape(), tuple->shape())) { return false; } } else if (top_tuple != operand->operand(0)) { return false; } } if (top_tuple == nullptr) { return false; } TF_ASSIGN_OR_RETURN(bool changed, tuple->parent()->ReplaceInstruction( tuple, top_tuple, /*preserve_sharding=*/true)); return changed; } absl::StatusOr<bool> TupleSimplifier::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { // Initially add all GTE and Tuple instructions to the worklist. bool changed = false; for (auto* computation : module->computations(execution_threads)) { if (exclude_entry_computation_ && computation == module->entry_computation()) { continue; } for (auto* instruction : computation->MakeInstructionPostOrder()) { if (instruction->opcode() == HloOpcode::kTuple) { TF_ASSIGN_OR_RETURN(bool c, RemoveWholeTuple(instruction)); changed |= c; } else { auto ancestor = instruction->LatestNonGteAncestorAndIndex(); if (ancestor.first == instruction) { continue; } // If possible replace a chain of GTE with the operation which produces // the element. For example, replace uses of GTE with below with just // 'Op' (assuming 'Op' is at the index of the GTE instruction): // // ... Op ... // \ | / // Tuple // | // GTE // ... // | // GTE // | // GTE // // Note that this deletes the Tuple instruction altogether. In addition, // if only a subset of tuple's elements are used, this transform // optimizes them one at a time, and after the last use is optimized, // the Tuple will also be deleted. HloInstruction* replacement = ancestor.first; for (int i = 0; i < ancestor.second.size(); ++i) { if (replacement->opcode() != HloOpcode::kTuple) { replacement = nullptr; break; } replacement = replacement->mutable_operand(ancestor.second[i]); } if (replacement) { TF_ASSIGN_OR_RETURN(bool replaced, computation->ReplaceInstruction( instruction, replacement, /*preserve_sharding=*/true, /*relay_control_dependency=*/true)); changed |= replaced; } } } } return changed; }
#include "xla/service/tuple_simplifier.h" #include <memory> #include <utility> #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/literal.h" #include "xla/shape_util.h" #include "xla/test.h" #include "xla/tests/hlo_test_base.h" #include "xla/types.h" #include "tsl/lib/core/status_test_util.h" class TupleSimplifierTest : public HloTestBase { protected: void Run(HloModule* module, bool change_expected) { auto changed_status = RunHloPass(TupleSimplifier(), module); TF_ASSERT_OK(changed_status.status()); EXPECT_EQ(change_expected, changed_status.value()); } void Run(HloModule* module, bool change_expected, bool exclude_entry) { auto changed_status = RunHloPass(TupleSimplifier(exclude_entry), module); TF_ASSERT_OK(changed_status.status()); EXPECT_EQ(change_expected, changed_status.value()); } const Shape scalar_shape_ = ShapeUtil::MakeShape(F32, {}); const Shape tuple_shape_ = ShapeUtil::MakeTupleShape( {ShapeUtil::MakeShape(F32, {}), ShapeUtil::MakeShape(F32, {}), ShapeUtil::MakeShape(F32, {})}); }; TEST_F(TupleSimplifierTest, GteOfTuple) { // A GTE of a Tuple should be short-circuited. HloComputation::Builder builder(TestName()); HloInstruction* param0 = builder.AddInstruction( HloInstruction::CreateParameter(0, scalar_shape_, "param0")); HloInstruction* param1 = builder.AddInstruction( HloInstruction::CreateParameter(1, scalar_shape_, "param1")); HloInstruction* param2 = builder.AddInstruction( HloInstruction::CreateParameter(2, scalar_shape_, "param2")); HloInstruction* tuple = builder.AddInstruction( HloInstruction::CreateTuple({param0, param1, param2})); HloInstruction* gte = builder.AddInstruction( HloInstruction::CreateGetTupleElement(scalar_shape_, tuple, 1)); auto module = CreateNewVerifiedModule(); auto computation = module->AddEntryComputation(builder.Build()); EXPECT_THAT(computation->root_instruction(), gte); Run(module.get(), /*change_expected=*/true); EXPECT_THAT(computation->root_instruction(), param1); }
TupleSimplifierTest_GteOfTupleChain
xla/service/tuple_simplifier_test.cc
TupleSimplifier::TupleSimplifier(bool exclude_entry_computation) : exclude_entry_computation_(exclude_entry_computation) {} absl::StatusOr<bool> TupleSimplifier::RemoveWholeTuple(HloInstruction* tuple) { HloInstruction* top_tuple = nullptr; for (int64_t operand_number = 0; operand_number < tuple->operand_count(); ++operand_number) { HloInstruction* operand = tuple->mutable_operand(operand_number); if (operand->opcode() != HloOpcode::kGetTupleElement || operand->tuple_index() != operand_number) { return false; } if (top_tuple == nullptr) { top_tuple = operand->mutable_operand(0); if (!ShapeUtil::Compatible(top_tuple->shape(), tuple->shape())) { return false; } } else if (top_tuple != operand->operand(0)) { return false; } } if (top_tuple == nullptr) { return false; } TF_ASSIGN_OR_RETURN(bool changed, tuple->parent()->ReplaceInstruction( tuple, top_tuple, /*preserve_sharding=*/true)); return changed; } absl::StatusOr<bool> TupleSimplifier::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { // Initially add all GTE and Tuple instructions to the worklist. bool changed = false; for (auto* computation : module->computations(execution_threads)) { if (exclude_entry_computation_ && computation == module->entry_computation()) { continue; } for (auto* instruction : computation->MakeInstructionPostOrder()) { if (instruction->opcode() == HloOpcode::kTuple) { TF_ASSIGN_OR_RETURN(bool c, RemoveWholeTuple(instruction)); changed |= c; } else { auto ancestor = instruction->LatestNonGteAncestorAndIndex(); if (ancestor.first == instruction) { continue; } // If possible replace a chain of GTE with the operation which produces // the element. For example, replace uses of GTE with below with just // 'Op' (assuming 'Op' is at the index of the GTE instruction): // // ... Op ... // \ | / // Tuple // | // GTE // ... // | // GTE // | // GTE // // Note that this deletes the Tuple instruction altogether. In addition, // if only a subset of tuple's elements are used, this transform // optimizes them one at a time, and after the last use is optimized, // the Tuple will also be deleted. HloInstruction* replacement = ancestor.first; for (int i = 0; i < ancestor.second.size(); ++i) { if (replacement->opcode() != HloOpcode::kTuple) { replacement = nullptr; break; } replacement = replacement->mutable_operand(ancestor.second[i]); } if (replacement) { TF_ASSIGN_OR_RETURN(bool replaced, computation->ReplaceInstruction( instruction, replacement, /*preserve_sharding=*/true, /*relay_control_dependency=*/true)); changed |= replaced; } } } } return changed; }
#include "xla/service/tuple_simplifier.h" #include <memory> #include <utility> #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/literal.h" #include "xla/shape_util.h" #include "xla/test.h" #include "xla/tests/hlo_test_base.h" #include "xla/types.h" #include "tsl/lib/core/status_test_util.h" class TupleSimplifierTest : public HloTestBase { protected: void Run(HloModule* module, bool change_expected) { auto changed_status = RunHloPass(TupleSimplifier(), module); TF_ASSERT_OK(changed_status.status()); EXPECT_EQ(change_expected, changed_status.value()); } void Run(HloModule* module, bool change_expected, bool exclude_entry) { auto changed_status = RunHloPass(TupleSimplifier(exclude_entry), module); TF_ASSERT_OK(changed_status.status()); EXPECT_EQ(change_expected, changed_status.value()); } const Shape scalar_shape_ = ShapeUtil::MakeShape(F32, {}); const Shape tuple_shape_ = ShapeUtil::MakeTupleShape( {ShapeUtil::MakeShape(F32, {}), ShapeUtil::MakeShape(F32, {}), ShapeUtil::MakeShape(F32, {})}); }; TEST_F(TupleSimplifierTest, GteOfTupleChain) { // Verify a chain of GTE/Tuple instructions is collapsed. HloComputation::Builder builder(TestName()); HloInstruction* param = builder.AddInstruction( HloInstruction::CreateParameter(0, scalar_shape_, "param")); const int kChainLength = 10; HloInstruction* element = param; for (int i = 0; i < kChainLength; ++i) { HloInstruction* tuple = builder.AddInstruction( HloInstruction::CreateTuple({element, element, element})); element = builder.AddInstruction( HloInstruction::CreateGetTupleElement(scalar_shape_, tuple, 1)); } builder.AddInstruction( HloInstruction::CreateUnary(scalar_shape_, HloOpcode::kNegate, element)); auto module = CreateNewVerifiedModule(); auto computation = module->AddEntryComputation(builder.Build()); EXPECT_THAT(computation->root_instruction(), op::Negate(op::GetTupleElement(op::Tuple()))); Run(module.get(), /*change_expected=*/true); EXPECT_THAT(computation->root_instruction(), op::Negate(op::Parameter())); }
TupleSimplifierTest_GteOfTupleOfParameter
xla/service/tuple_simplifier_test.cc
TupleSimplifier::TupleSimplifier(bool exclude_entry_computation) : exclude_entry_computation_(exclude_entry_computation) {} absl::StatusOr<bool> TupleSimplifier::RemoveWholeTuple(HloInstruction* tuple) { HloInstruction* top_tuple = nullptr; for (int64_t operand_number = 0; operand_number < tuple->operand_count(); ++operand_number) { HloInstruction* operand = tuple->mutable_operand(operand_number); if (operand->opcode() != HloOpcode::kGetTupleElement || operand->tuple_index() != operand_number) { return false; } if (top_tuple == nullptr) { top_tuple = operand->mutable_operand(0); if (!ShapeUtil::Compatible(top_tuple->shape(), tuple->shape())) { return false; } } else if (top_tuple != operand->operand(0)) { return false; } } if (top_tuple == nullptr) { return false; } TF_ASSIGN_OR_RETURN(bool changed, tuple->parent()->ReplaceInstruction( tuple, top_tuple, /*preserve_sharding=*/true)); return changed; } absl::StatusOr<bool> TupleSimplifier::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { // Initially add all GTE and Tuple instructions to the worklist. bool changed = false; for (auto* computation : module->computations(execution_threads)) { if (exclude_entry_computation_ && computation == module->entry_computation()) { continue; } for (auto* instruction : computation->MakeInstructionPostOrder()) { if (instruction->opcode() == HloOpcode::kTuple) { TF_ASSIGN_OR_RETURN(bool c, RemoveWholeTuple(instruction)); changed |= c; } else { auto ancestor = instruction->LatestNonGteAncestorAndIndex(); if (ancestor.first == instruction) { continue; } // If possible replace a chain of GTE with the operation which produces // the element. For example, replace uses of GTE with below with just // 'Op' (assuming 'Op' is at the index of the GTE instruction): // // ... Op ... // \ | / // Tuple // | // GTE // ... // | // GTE // | // GTE // // Note that this deletes the Tuple instruction altogether. In addition, // if only a subset of tuple's elements are used, this transform // optimizes them one at a time, and after the last use is optimized, // the Tuple will also be deleted. HloInstruction* replacement = ancestor.first; for (int i = 0; i < ancestor.second.size(); ++i) { if (replacement->opcode() != HloOpcode::kTuple) { replacement = nullptr; break; } replacement = replacement->mutable_operand(ancestor.second[i]); } if (replacement) { TF_ASSIGN_OR_RETURN(bool replaced, computation->ReplaceInstruction( instruction, replacement, /*preserve_sharding=*/true, /*relay_control_dependency=*/true)); changed |= replaced; } } } } return changed; }
#include "xla/service/tuple_simplifier.h" #include <memory> #include <utility> #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/literal.h" #include "xla/shape_util.h" #include "xla/test.h" #include "xla/tests/hlo_test_base.h" #include "xla/types.h" #include "tsl/lib/core/status_test_util.h" class TupleSimplifierTest : public HloTestBase { protected: void Run(HloModule* module, bool change_expected) { auto changed_status = RunHloPass(TupleSimplifier(), module); TF_ASSERT_OK(changed_status.status()); EXPECT_EQ(change_expected, changed_status.value()); } void Run(HloModule* module, bool change_expected, bool exclude_entry) { auto changed_status = RunHloPass(TupleSimplifier(exclude_entry), module); TF_ASSERT_OK(changed_status.status()); EXPECT_EQ(change_expected, changed_status.value()); } const Shape scalar_shape_ = ShapeUtil::MakeShape(F32, {}); const Shape tuple_shape_ = ShapeUtil::MakeTupleShape( {ShapeUtil::MakeShape(F32, {}), ShapeUtil::MakeShape(F32, {}), ShapeUtil::MakeShape(F32, {})}); }; TEST_F(TupleSimplifierTest, GteOfTupleOfParameter) { // A GTE of a tuple parameter should not be changed. HloComputation::Builder builder(TestName()); HloInstruction* param = builder.AddInstruction( HloInstruction::CreateParameter(0, tuple_shape_, "param")); builder.AddInstruction( HloInstruction::CreateGetTupleElement(scalar_shape_, param, 1)); auto module = CreateNewVerifiedModule(); module->AddEntryComputation(builder.Build()); Run(module.get(), /*change_expected=*/false); }
TupleSimplifierTest_IncompatibleTuples
xla/service/tuple_simplifier_test.cc
TupleSimplifier::TupleSimplifier(bool exclude_entry_computation) : exclude_entry_computation_(exclude_entry_computation) {} absl::StatusOr<bool> TupleSimplifier::RemoveWholeTuple(HloInstruction* tuple) { HloInstruction* top_tuple = nullptr; for (int64_t operand_number = 0; operand_number < tuple->operand_count(); ++operand_number) { HloInstruction* operand = tuple->mutable_operand(operand_number); if (operand->opcode() != HloOpcode::kGetTupleElement || operand->tuple_index() != operand_number) { return false; } if (top_tuple == nullptr) { top_tuple = operand->mutable_operand(0); if (!ShapeUtil::Compatible(top_tuple->shape(), tuple->shape())) { return false; } } else if (top_tuple != operand->operand(0)) { return false; } } if (top_tuple == nullptr) { return false; } TF_ASSIGN_OR_RETURN(bool changed, tuple->parent()->ReplaceInstruction( tuple, top_tuple, /*preserve_sharding=*/true)); return changed; } absl::StatusOr<bool> TupleSimplifier::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { // Initially add all GTE and Tuple instructions to the worklist. bool changed = false; for (auto* computation : module->computations(execution_threads)) { if (exclude_entry_computation_ && computation == module->entry_computation()) { continue; } for (auto* instruction : computation->MakeInstructionPostOrder()) { if (instruction->opcode() == HloOpcode::kTuple) { TF_ASSIGN_OR_RETURN(bool c, RemoveWholeTuple(instruction)); changed |= c; } else { auto ancestor = instruction->LatestNonGteAncestorAndIndex(); if (ancestor.first == instruction) { continue; } // If possible replace a chain of GTE with the operation which produces // the element. For example, replace uses of GTE with below with just // 'Op' (assuming 'Op' is at the index of the GTE instruction): // // ... Op ... // \ | / // Tuple // | // GTE // ... // | // GTE // | // GTE // // Note that this deletes the Tuple instruction altogether. In addition, // if only a subset of tuple's elements are used, this transform // optimizes them one at a time, and after the last use is optimized, // the Tuple will also be deleted. HloInstruction* replacement = ancestor.first; for (int i = 0; i < ancestor.second.size(); ++i) { if (replacement->opcode() != HloOpcode::kTuple) { replacement = nullptr; break; } replacement = replacement->mutable_operand(ancestor.second[i]); } if (replacement) { TF_ASSIGN_OR_RETURN(bool replaced, computation->ReplaceInstruction( instruction, replacement, /*preserve_sharding=*/true, /*relay_control_dependency=*/true)); changed |= replaced; } } } } return changed; }
#include "xla/service/tuple_simplifier.h" #include <memory> #include <utility> #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/literal.h" #include "xla/shape_util.h" #include "xla/test.h" #include "xla/tests/hlo_test_base.h" #include "xla/types.h" #include "tsl/lib/core/status_test_util.h" class TupleSimplifierTest : public HloTestBase { protected: void Run(HloModule* module, bool change_expected) { auto changed_status = RunHloPass(TupleSimplifier(), module); TF_ASSERT_OK(changed_status.status()); EXPECT_EQ(change_expected, changed_status.value()); } void Run(HloModule* module, bool change_expected, bool exclude_entry) { auto changed_status = RunHloPass(TupleSimplifier(exclude_entry), module); TF_ASSERT_OK(changed_status.status()); EXPECT_EQ(change_expected, changed_status.value()); } const Shape scalar_shape_ = ShapeUtil::MakeShape(F32, {}); const Shape tuple_shape_ = ShapeUtil::MakeTupleShape( {ShapeUtil::MakeShape(F32, {}), ShapeUtil::MakeShape(F32, {}), ShapeUtil::MakeShape(F32, {})}); }; TEST_F(TupleSimplifierTest, IncompatibleTuples) { // Verify that a tuple->GTE->tuple construct is not simplified if the input // and output tuple are not compatible shapes. HloComputation::Builder builder(TestName()); HloInstruction* tuple_param = builder.AddInstruction( HloInstruction::CreateParameter(0, tuple_shape_, "param")); HloInstruction* gte0 = builder.AddInstruction( HloInstruction::CreateGetTupleElement(scalar_shape_, tuple_param, 0)); HloInstruction* gte1 = builder.AddInstruction( HloInstruction::CreateGetTupleElement(scalar_shape_, tuple_param, 1)); // Output tuple has only two elements. Parameter tuple has three elements so // simplification is not possible. HloInstruction* tuple = builder.AddInstruction(HloInstruction::CreateTuple({gte0, gte1})); auto module = CreateNewVerifiedModule(); auto computation = module->AddEntryComputation(builder.Build()); EXPECT_THAT(computation->root_instruction(), tuple); Run(module.get(), /*change_expected=*/false); EXPECT_THAT(computation->root_instruction(), tuple); }
TupleSimplifierTest_NestedGteOfTuples
xla/service/tuple_simplifier_test.cc
TupleSimplifier::TupleSimplifier(bool exclude_entry_computation) : exclude_entry_computation_(exclude_entry_computation) {} absl::StatusOr<bool> TupleSimplifier::RemoveWholeTuple(HloInstruction* tuple) { HloInstruction* top_tuple = nullptr; for (int64_t operand_number = 0; operand_number < tuple->operand_count(); ++operand_number) { HloInstruction* operand = tuple->mutable_operand(operand_number); if (operand->opcode() != HloOpcode::kGetTupleElement || operand->tuple_index() != operand_number) { return false; } if (top_tuple == nullptr) { top_tuple = operand->mutable_operand(0); if (!ShapeUtil::Compatible(top_tuple->shape(), tuple->shape())) { return false; } } else if (top_tuple != operand->operand(0)) { return false; } } if (top_tuple == nullptr) { return false; } TF_ASSIGN_OR_RETURN(bool changed, tuple->parent()->ReplaceInstruction( tuple, top_tuple, /*preserve_sharding=*/true)); return changed; } absl::StatusOr<bool> TupleSimplifier::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { // Initially add all GTE and Tuple instructions to the worklist. bool changed = false; for (auto* computation : module->computations(execution_threads)) { if (exclude_entry_computation_ && computation == module->entry_computation()) { continue; } for (auto* instruction : computation->MakeInstructionPostOrder()) { if (instruction->opcode() == HloOpcode::kTuple) { TF_ASSIGN_OR_RETURN(bool c, RemoveWholeTuple(instruction)); changed |= c; } else { auto ancestor = instruction->LatestNonGteAncestorAndIndex(); if (ancestor.first == instruction) { continue; } // If possible replace a chain of GTE with the operation which produces // the element. For example, replace uses of GTE with below with just // 'Op' (assuming 'Op' is at the index of the GTE instruction): // // ... Op ... // \ | / // Tuple // | // GTE // ... // | // GTE // | // GTE // // Note that this deletes the Tuple instruction altogether. In addition, // if only a subset of tuple's elements are used, this transform // optimizes them one at a time, and after the last use is optimized, // the Tuple will also be deleted. HloInstruction* replacement = ancestor.first; for (int i = 0; i < ancestor.second.size(); ++i) { if (replacement->opcode() != HloOpcode::kTuple) { replacement = nullptr; break; } replacement = replacement->mutable_operand(ancestor.second[i]); } if (replacement) { TF_ASSIGN_OR_RETURN(bool replaced, computation->ReplaceInstruction( instruction, replacement, /*preserve_sharding=*/true, /*relay_control_dependency=*/true)); changed |= replaced; } } } } return changed; }
#include "xla/service/tuple_simplifier.h" #include <memory> #include <utility> #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/literal.h" #include "xla/shape_util.h" #include "xla/test.h" #include "xla/tests/hlo_test_base.h" #include "xla/types.h" #include "tsl/lib/core/status_test_util.h" class TupleSimplifierTest : public HloTestBase { protected: void Run(HloModule* module, bool change_expected) { auto changed_status = RunHloPass(TupleSimplifier(), module); TF_ASSERT_OK(changed_status.status()); EXPECT_EQ(change_expected, changed_status.value()); } void Run(HloModule* module, bool change_expected, bool exclude_entry) { auto changed_status = RunHloPass(TupleSimplifier(exclude_entry), module); TF_ASSERT_OK(changed_status.status()); EXPECT_EQ(change_expected, changed_status.value()); } const Shape scalar_shape_ = ShapeUtil::MakeShape(F32, {}); const Shape tuple_shape_ = ShapeUtil::MakeTupleShape( {ShapeUtil::MakeShape(F32, {}), ShapeUtil::MakeShape(F32, {}), ShapeUtil::MakeShape(F32, {})}); }; TEST_F(TupleSimplifierTest, NestedGteOfTuples) { // Verify a nesting of GTE/Tuple instructions is collapsed. Tuples are nested // to some depth with a chain of Tuple instructions, then extracted with a // chain of GTE instructions. HloComputation::Builder builder(TestName()); HloInstruction* param = builder.AddInstruction( HloInstruction::CreateParameter(0, scalar_shape_, "param")); const int kNestingDepth = 5; HloInstruction* nested_tuple = param; for (int i = 0; i < kNestingDepth; ++i) { nested_tuple = builder.AddInstruction( HloInstruction::CreateTuple({nested_tuple, nested_tuple})); } HloInstruction* element = nested_tuple; for (int i = 0; i < kNestingDepth; ++i) { element = builder.AddInstruction(HloInstruction::CreateGetTupleElement( ShapeUtil::GetTupleElementShape(element->shape(), 0), element, 0)); } auto module = CreateNewVerifiedModule(); auto computation = module->AddEntryComputation(builder.Build()); EXPECT_THAT(computation->root_instruction(), element); Run(module.get(), /*change_expected=*/true); EXPECT_THAT(computation->root_instruction(), param); }
TupleSimplifierTest_NestedTuple
xla/service/tuple_simplifier_test.cc
TupleSimplifier::TupleSimplifier(bool exclude_entry_computation) : exclude_entry_computation_(exclude_entry_computation) {} absl::StatusOr<bool> TupleSimplifier::RemoveWholeTuple(HloInstruction* tuple) { HloInstruction* top_tuple = nullptr; for (int64_t operand_number = 0; operand_number < tuple->operand_count(); ++operand_number) { HloInstruction* operand = tuple->mutable_operand(operand_number); if (operand->opcode() != HloOpcode::kGetTupleElement || operand->tuple_index() != operand_number) { return false; } if (top_tuple == nullptr) { top_tuple = operand->mutable_operand(0); if (!ShapeUtil::Compatible(top_tuple->shape(), tuple->shape())) { return false; } } else if (top_tuple != operand->operand(0)) { return false; } } if (top_tuple == nullptr) { return false; } TF_ASSIGN_OR_RETURN(bool changed, tuple->parent()->ReplaceInstruction( tuple, top_tuple, /*preserve_sharding=*/true)); return changed; } absl::StatusOr<bool> TupleSimplifier::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { // Initially add all GTE and Tuple instructions to the worklist. bool changed = false; for (auto* computation : module->computations(execution_threads)) { if (exclude_entry_computation_ && computation == module->entry_computation()) { continue; } for (auto* instruction : computation->MakeInstructionPostOrder()) { if (instruction->opcode() == HloOpcode::kTuple) { TF_ASSIGN_OR_RETURN(bool c, RemoveWholeTuple(instruction)); changed |= c; } else { auto ancestor = instruction->LatestNonGteAncestorAndIndex(); if (ancestor.first == instruction) { continue; } // If possible replace a chain of GTE with the operation which produces // the element. For example, replace uses of GTE with below with just // 'Op' (assuming 'Op' is at the index of the GTE instruction): // // ... Op ... // \ | / // Tuple // | // GTE // ... // | // GTE // | // GTE // // Note that this deletes the Tuple instruction altogether. In addition, // if only a subset of tuple's elements are used, this transform // optimizes them one at a time, and after the last use is optimized, // the Tuple will also be deleted. HloInstruction* replacement = ancestor.first; for (int i = 0; i < ancestor.second.size(); ++i) { if (replacement->opcode() != HloOpcode::kTuple) { replacement = nullptr; break; } replacement = replacement->mutable_operand(ancestor.second[i]); } if (replacement) { TF_ASSIGN_OR_RETURN(bool replaced, computation->ReplaceInstruction( instruction, replacement, /*preserve_sharding=*/true, /*relay_control_dependency=*/true)); changed |= replaced; } } } } return changed; }
#include "xla/service/tuple_simplifier.h" #include <memory> #include <utility> #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/literal.h" #include "xla/shape_util.h" #include "xla/test.h" #include "xla/tests/hlo_test_base.h" #include "xla/types.h" #include "tsl/lib/core/status_test_util.h" class TupleSimplifierTest : public HloTestBase { protected: void Run(HloModule* module, bool change_expected) { auto changed_status = RunHloPass(TupleSimplifier(), module); TF_ASSERT_OK(changed_status.status()); EXPECT_EQ(change_expected, changed_status.value()); } void Run(HloModule* module, bool change_expected, bool exclude_entry) { auto changed_status = RunHloPass(TupleSimplifier(exclude_entry), module); TF_ASSERT_OK(changed_status.status()); EXPECT_EQ(change_expected, changed_status.value()); } const Shape scalar_shape_ = ShapeUtil::MakeShape(F32, {}); const Shape tuple_shape_ = ShapeUtil::MakeTupleShape( {ShapeUtil::MakeShape(F32, {}), ShapeUtil::MakeShape(F32, {}), ShapeUtil::MakeShape(F32, {})}); };
TupleSimplifierTest_ShardingLoss
xla/service/tuple_simplifier_test.cc
TupleSimplifier::TupleSimplifier(bool exclude_entry_computation) : exclude_entry_computation_(exclude_entry_computation) {} absl::StatusOr<bool> TupleSimplifier::RemoveWholeTuple(HloInstruction* tuple) { HloInstruction* top_tuple = nullptr; for (int64_t operand_number = 0; operand_number < tuple->operand_count(); ++operand_number) { HloInstruction* operand = tuple->mutable_operand(operand_number); if (operand->opcode() != HloOpcode::kGetTupleElement || operand->tuple_index() != operand_number) { return false; } if (top_tuple == nullptr) { top_tuple = operand->mutable_operand(0); if (!ShapeUtil::Compatible(top_tuple->shape(), tuple->shape())) { return false; } } else if (top_tuple != operand->operand(0)) { return false; } } if (top_tuple == nullptr) { return false; } TF_ASSIGN_OR_RETURN(bool changed, tuple->parent()->ReplaceInstruction( tuple, top_tuple, /*preserve_sharding=*/true)); return changed; } absl::StatusOr<bool> TupleSimplifier::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { // Initially add all GTE and Tuple instructions to the worklist. bool changed = false; for (auto* computation : module->computations(execution_threads)) { if (exclude_entry_computation_ && computation == module->entry_computation()) { continue; } for (auto* instruction : computation->MakeInstructionPostOrder()) { if (instruction->opcode() == HloOpcode::kTuple) { TF_ASSIGN_OR_RETURN(bool c, RemoveWholeTuple(instruction)); changed |= c; } else { auto ancestor = instruction->LatestNonGteAncestorAndIndex(); if (ancestor.first == instruction) { continue; } // If possible replace a chain of GTE with the operation which produces // the element. For example, replace uses of GTE with below with just // 'Op' (assuming 'Op' is at the index of the GTE instruction): // // ... Op ... // \ | / // Tuple // | // GTE // ... // | // GTE // | // GTE // // Note that this deletes the Tuple instruction altogether. In addition, // if only a subset of tuple's elements are used, this transform // optimizes them one at a time, and after the last use is optimized, // the Tuple will also be deleted. HloInstruction* replacement = ancestor.first; for (int i = 0; i < ancestor.second.size(); ++i) { if (replacement->opcode() != HloOpcode::kTuple) { replacement = nullptr; break; } replacement = replacement->mutable_operand(ancestor.second[i]); } if (replacement) { TF_ASSIGN_OR_RETURN(bool replaced, computation->ReplaceInstruction( instruction, replacement, /*preserve_sharding=*/true, /*relay_control_dependency=*/true)); changed |= replaced; } } } } return changed; }
#include "xla/service/tuple_simplifier.h" #include <memory> #include <utility> #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/literal.h" #include "xla/shape_util.h" #include "xla/test.h" #include "xla/tests/hlo_test_base.h" #include "xla/types.h" #include "tsl/lib/core/status_test_util.h" class TupleSimplifierTest : public HloTestBase { protected: void Run(HloModule* module, bool change_expected) { auto changed_status = RunHloPass(TupleSimplifier(), module); TF_ASSERT_OK(changed_status.status()); EXPECT_EQ(change_expected, changed_status.value()); } void Run(HloModule* module, bool change_expected, bool exclude_entry) { auto changed_status = RunHloPass(TupleSimplifier(exclude_entry), module); TF_ASSERT_OK(changed_status.status()); EXPECT_EQ(change_expected, changed_status.value()); } const Shape scalar_shape_ = ShapeUtil::MakeShape(F32, {}); const Shape tuple_shape_ = ShapeUtil::MakeTupleShape( {ShapeUtil::MakeShape(F32, {}), ShapeUtil::MakeShape(F32, {}), ShapeUtil::MakeShape(F32, {})}); }; TEST_F(TupleSimplifierTest, ShardingLoss) { const char* kModuleStr = R"( HloModule m ENTRY test { p0 = s32[10] parameter(0), sharding={devices=[2]0,1} t = (s32[10]) tuple(p0) ROOT %gte = s32[10] get-tuple-element(t), index=0, sharding={replicated} } )"; TF_ASSERT_OK_AND_ASSIGN(auto m, ParseAndReturnVerifiedModule(kModuleStr)); Run(m.get(), /*change_expected=*/false); }
TupleSimplifierTest_TupleOfGteInstructions
xla/service/tuple_simplifier_test.cc
TupleSimplifier::TupleSimplifier(bool exclude_entry_computation) : exclude_entry_computation_(exclude_entry_computation) {} absl::StatusOr<bool> TupleSimplifier::RemoveWholeTuple(HloInstruction* tuple) { HloInstruction* top_tuple = nullptr; for (int64_t operand_number = 0; operand_number < tuple->operand_count(); ++operand_number) { HloInstruction* operand = tuple->mutable_operand(operand_number); if (operand->opcode() != HloOpcode::kGetTupleElement || operand->tuple_index() != operand_number) { return false; } if (top_tuple == nullptr) { top_tuple = operand->mutable_operand(0); if (!ShapeUtil::Compatible(top_tuple->shape(), tuple->shape())) { return false; } } else if (top_tuple != operand->operand(0)) { return false; } } if (top_tuple == nullptr) { return false; } TF_ASSIGN_OR_RETURN(bool changed, tuple->parent()->ReplaceInstruction( tuple, top_tuple, /*preserve_sharding=*/true)); return changed; } absl::StatusOr<bool> TupleSimplifier::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { // Initially add all GTE and Tuple instructions to the worklist. bool changed = false; for (auto* computation : module->computations(execution_threads)) { if (exclude_entry_computation_ && computation == module->entry_computation()) { continue; } for (auto* instruction : computation->MakeInstructionPostOrder()) { if (instruction->opcode() == HloOpcode::kTuple) { TF_ASSIGN_OR_RETURN(bool c, RemoveWholeTuple(instruction)); changed |= c; } else { auto ancestor = instruction->LatestNonGteAncestorAndIndex(); if (ancestor.first == instruction) { continue; } // If possible replace a chain of GTE with the operation which produces // the element. For example, replace uses of GTE with below with just // 'Op' (assuming 'Op' is at the index of the GTE instruction): // // ... Op ... // \ | / // Tuple // | // GTE // ... // | // GTE // | // GTE // // Note that this deletes the Tuple instruction altogether. In addition, // if only a subset of tuple's elements are used, this transform // optimizes them one at a time, and after the last use is optimized, // the Tuple will also be deleted. HloInstruction* replacement = ancestor.first; for (int i = 0; i < ancestor.second.size(); ++i) { if (replacement->opcode() != HloOpcode::kTuple) { replacement = nullptr; break; } replacement = replacement->mutable_operand(ancestor.second[i]); } if (replacement) { TF_ASSIGN_OR_RETURN(bool replaced, computation->ReplaceInstruction( instruction, replacement, /*preserve_sharding=*/true, /*relay_control_dependency=*/true)); changed |= replaced; } } } } return changed; }
#include "xla/service/tuple_simplifier.h" #include <memory> #include <utility> #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/literal.h" #include "xla/shape_util.h" #include "xla/test.h" #include "xla/tests/hlo_test_base.h" #include "xla/types.h" #include "tsl/lib/core/status_test_util.h" class TupleSimplifierTest : public HloTestBase { protected: void Run(HloModule* module, bool change_expected) { auto changed_status = RunHloPass(TupleSimplifier(), module); TF_ASSERT_OK(changed_status.status()); EXPECT_EQ(change_expected, changed_status.value()); } void Run(HloModule* module, bool change_expected, bool exclude_entry) { auto changed_status = RunHloPass(TupleSimplifier(exclude_entry), module); TF_ASSERT_OK(changed_status.status()); EXPECT_EQ(change_expected, changed_status.value()); } const Shape scalar_shape_ = ShapeUtil::MakeShape(F32, {}); const Shape tuple_shape_ = ShapeUtil::MakeTupleShape( {ShapeUtil::MakeShape(F32, {}), ShapeUtil::MakeShape(F32, {}), ShapeUtil::MakeShape(F32, {})}); }; TEST_F(TupleSimplifierTest, TupleOfGteInstructions) { // Verify that a tuple constructed of GTE instructions operating on the same // tuple are collapsed. HloComputation::Builder builder(TestName()); HloInstruction* tuple_param = builder.AddInstruction( HloInstruction::CreateParameter(0, tuple_shape_, "param")); HloInstruction* gte0 = builder.AddInstruction( HloInstruction::CreateGetTupleElement(scalar_shape_, tuple_param, 0)); HloInstruction* gte1 = builder.AddInstruction( HloInstruction::CreateGetTupleElement(scalar_shape_, tuple_param, 1)); HloInstruction* gte2 = builder.AddInstruction( HloInstruction::CreateGetTupleElement(scalar_shape_, tuple_param, 2)); HloInstruction* tuple = builder.AddInstruction(HloInstruction::CreateTuple({gte0, gte1, gte2})); auto module = CreateNewVerifiedModule(); auto computation = module->AddEntryComputation(builder.Build()); EXPECT_THAT(computation->root_instruction(), tuple); Run(module.get(), /*change_expected=*/true); EXPECT_THAT(computation->root_instruction(), tuple_param); }
TupleSimplifierTest_TupleOfParameters
xla/service/tuple_simplifier_test.cc
TupleSimplifier::TupleSimplifier(bool exclude_entry_computation) : exclude_entry_computation_(exclude_entry_computation) {} absl::StatusOr<bool> TupleSimplifier::RemoveWholeTuple(HloInstruction* tuple) { HloInstruction* top_tuple = nullptr; for (int64_t operand_number = 0; operand_number < tuple->operand_count(); ++operand_number) { HloInstruction* operand = tuple->mutable_operand(operand_number); if (operand->opcode() != HloOpcode::kGetTupleElement || operand->tuple_index() != operand_number) { return false; } if (top_tuple == nullptr) { top_tuple = operand->mutable_operand(0); if (!ShapeUtil::Compatible(top_tuple->shape(), tuple->shape())) { return false; } } else if (top_tuple != operand->operand(0)) { return false; } } if (top_tuple == nullptr) { return false; } TF_ASSIGN_OR_RETURN(bool changed, tuple->parent()->ReplaceInstruction( tuple, top_tuple, /*preserve_sharding=*/true)); return changed; } absl::StatusOr<bool> TupleSimplifier::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { // Initially add all GTE and Tuple instructions to the worklist. bool changed = false; for (auto* computation : module->computations(execution_threads)) { if (exclude_entry_computation_ && computation == module->entry_computation()) { continue; } for (auto* instruction : computation->MakeInstructionPostOrder()) { if (instruction->opcode() == HloOpcode::kTuple) { TF_ASSIGN_OR_RETURN(bool c, RemoveWholeTuple(instruction)); changed |= c; } else { auto ancestor = instruction->LatestNonGteAncestorAndIndex(); if (ancestor.first == instruction) { continue; } // If possible replace a chain of GTE with the operation which produces // the element. For example, replace uses of GTE with below with just // 'Op' (assuming 'Op' is at the index of the GTE instruction): // // ... Op ... // \ | / // Tuple // | // GTE // ... // | // GTE // | // GTE // // Note that this deletes the Tuple instruction altogether. In addition, // if only a subset of tuple's elements are used, this transform // optimizes them one at a time, and after the last use is optimized, // the Tuple will also be deleted. HloInstruction* replacement = ancestor.first; for (int i = 0; i < ancestor.second.size(); ++i) { if (replacement->opcode() != HloOpcode::kTuple) { replacement = nullptr; break; } replacement = replacement->mutable_operand(ancestor.second[i]); } if (replacement) { TF_ASSIGN_OR_RETURN(bool replaced, computation->ReplaceInstruction( instruction, replacement, /*preserve_sharding=*/true, /*relay_control_dependency=*/true)); changed |= replaced; } } } } return changed; }
#include "xla/service/tuple_simplifier.h" #include <memory> #include <utility> #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/literal.h" #include "xla/shape_util.h" #include "xla/test.h" #include "xla/tests/hlo_test_base.h" #include "xla/types.h" #include "tsl/lib/core/status_test_util.h" class TupleSimplifierTest : public HloTestBase { protected: void Run(HloModule* module, bool change_expected) { auto changed_status = RunHloPass(TupleSimplifier(), module); TF_ASSERT_OK(changed_status.status()); EXPECT_EQ(change_expected, changed_status.value()); } void Run(HloModule* module, bool change_expected, bool exclude_entry) { auto changed_status = RunHloPass(TupleSimplifier(exclude_entry), module); TF_ASSERT_OK(changed_status.status()); EXPECT_EQ(change_expected, changed_status.value()); } const Shape scalar_shape_ = ShapeUtil::MakeShape(F32, {}); const Shape tuple_shape_ = ShapeUtil::MakeTupleShape( {ShapeUtil::MakeShape(F32, {}), ShapeUtil::MakeShape(F32, {}), ShapeUtil::MakeShape(F32, {})}); }; TEST_F(TupleSimplifierTest, TupleOfParameters) { // A Tuple constructed of a bunch of parameters should not be changed. HloComputation::Builder builder(TestName()); HloInstruction* param0 = builder.AddInstruction( HloInstruction::CreateParameter(0, scalar_shape_, "param0")); HloInstruction* param1 = builder.AddInstruction( HloInstruction::CreateParameter(1, scalar_shape_, "param1")); HloInstruction* param2 = builder.AddInstruction( HloInstruction::CreateParameter(2, scalar_shape_, "param2")); builder.AddInstruction(HloInstruction::CreateTuple({param0, param1, param2})); auto module = CreateNewVerifiedModule(); module->AddEntryComputation(builder.Build()); Run(module.get(), /*change_expected=*/false); }
ArrayTest_Destruction
xla/python/ifrt_proxy/client/array_test.cc
Array::MakeArrayFromHostBuffer( xla::ifrt::Client* client, std::shared_ptr<RpcHelper> rpc_helper, const void* data, DType dtype, Shape shape, std::optional<absl::Span<const int64_t>> byte_strides, std::shared_ptr<const Sharding> sharding, xla::ifrt::Client::HostBufferSemantics semantics, std::function<void()> on_done_with_host_buffer) { TF_ASSIGN_OR_RETURN(const auto array_mem_region, ArrayMemRegion::FromZerothElementPointer( /*zeroth_element=*/data, dtype, shape, byte_strides)); const uint64_t host_buffer_handle = rpc_helper->host_buffer_store()->NextHandle(); TF_RETURN_IF_ERROR( rpc_helper->host_buffer_store() ->Store(host_buffer_handle, array_mem_region.mem_region()) .Await()); auto req = std::make_unique<MakeArrayFromHostBufferRequest>(); req->set_host_buffer_handle(host_buffer_handle); *req->mutable_dtype() = dtype.ToProto(); *req->mutable_shape() = shape.ToProto(); TF_ASSIGN_OR_RETURN(*req->mutable_sharding(), sharding->ToProto()); if (byte_strides.has_value()) { *req->mutable_byte_strides() = ToByteStridesProto(*byte_strides); } TF_ASSIGN_OR_RETURN( auto response, rpc_helper->MakeArrayFromHostBuffer(std::move(req)).Await()); const ArrayHandle handle{response->array_handle()}; if (on_done_with_host_buffer != nullptr) { std::move(on_done_with_host_buffer)(); } return tsl::RCReference<xla::ifrt::Array>( tsl::MakeRef<Array>(client, std::move(rpc_helper), dtype, std::move(shape), std::move(sharding), handle)); } void Array::Destruct(RpcHelper* rpc_helper, ArrayHandle handle) { auto req = std::make_unique<DestructArrayRequest>(); req->set_array_handle(handle.handle); rpc_helper->DestructArray(std::move(req)) .OnReady( [](absl::StatusOr<std::shared_ptr<DestructArrayResponse>> response) { if (!response.ok()) { LOG(WARNING) << "Server returned an error when asked to destruct array: " << response.status(); } }); } [](absl::StatusOr<std::shared_ptr<DestructArrayResponse>> response) { if (!response.ok()) { LOG(WARNING) << "Server returned an error when asked to destruct array: " << response.status(); } }); Future<> Array::GetReadyFuture() const { auto req = std::make_unique<CheckValueReadyRequest>(); req->add_value_handles(handle_.handle); auto promise = Future<>::CreatePromise(); rpc_helper_->CheckValueReady(std::move(req)) .OnReady( [promise](absl::StatusOr<std::shared_ptr<CheckValueReadyResponse>> resp) mutable { promise.Set(resp.status()); }); return Future<>(std::move(promise)); } [promise](absl::StatusOr<std::shared_ptr<CheckValueReadyResponse>> resp) mutable { promise.Set(resp.status()); }); Future<> Array::Delete() { auto req = std::make_unique<DeleteArrayRequest>(); req->set_array_handle(handle_.handle); absl::StatusOr<std::shared_ptr<DeleteArrayResponse>> response = rpc_helper_->DeleteArray(std::move(req)).Await(); if (!response.ok()) { return Future<>(response.status()); } // TODO(b/266635130): So that the caller is not blocked until the server // replies with the deletion's response, from within // `Future(status_handle_promise).OnReady()`, schedule `CheckFuture()` on a // separate thread. return rpc_helper_->CheckFuture((*response)->deletion_future_handle()); } bool Array::IsDeleted() const { auto req = std::make_unique<IsArrayDeletedRequest>(); req->set_array_handle(handle_.handle); absl::StatusOr<std::shared_ptr<IsArrayDeletedResponse>> response = rpc_helper_->IsArrayDeleted(std::move(req)).Await(); if (response.ok()) { return (*response)->deleted(); } else { LOG(ERROR) << "Internal error from proxy server during Array::IsDeleted(): " << response.status(); // Return false so that the user likely queries the array with some // method that returns an absl::Status, and ends up with the real // error being returned to them by that method. return false; } } Array::AssembleArrayFromSingleDeviceArrays( xla::ifrt::Client* client, std::shared_ptr<RpcHelper> rpc_helper, Shape shape, std::shared_ptr<const Sharding> sharding, absl::Span<tsl::RCReference<xla::ifrt::Array>> arrays, ArrayCopySemantics semantics) { auto req = std::make_unique<AssembleArrayFromSingleDeviceArraysRequest>(); TF_RET_CHECK(!arrays.empty()); *req->mutable_shape() = shape.ToProto(); TF_ASSIGN_OR_RETURN(*req->mutable_sharding(), sharding->ToProto()); req->set_copy_semantics(ToArrayCopySemanticsProto(semantics)); for (const tsl::RCReference<xla::ifrt::Array>& rcref : arrays) { Array* array = llvm::dyn_cast<Array>(rcref.get()); if (array == nullptr) { return absl::InvalidArgumentError(absl::Substitute( "Array at $0 supplied to AssembleArrayFromSingleDeviceArrays() is " "not a xla::ifrt::proxy::Array.", rcref.get())); } req->add_single_device_array_handles(array->handle_.handle); } TF_ASSIGN_OR_RETURN( std::shared_ptr<AssembleArrayFromSingleDeviceArraysResponse> response, rpc_helper->AssembleArrayFromSingleDeviceArrays(std::move(req)).Await()); ArrayHandle handle{response->array_handle()}; return tsl::RCReference<xla::ifrt::Array>( tsl::MakeRef<Array>(client, std::move(rpc_helper), arrays[0]->dtype(), std::move(shape), std::move(sharding), handle)); } Array::RemapArrays(xla::ifrt::Client* client, std::shared_ptr<RpcHelper> rpc_helper, const RemapPlan& plan, absl::Span<tsl::RCReference<xla::ifrt::Array>> arrays, ArrayCopySemantics semantics) { auto req = std::make_unique<RemapArraysRequest>(); TF_RET_CHECK(!arrays.empty()); TF_ASSIGN_OR_RETURN(*req->mutable_plan(), plan.ToProto()); req->set_copy_semantics(ToArrayCopySemanticsProto(semantics)); for (const tsl::RCReference<xla::ifrt::Array>& rcref : arrays) { Array* array = llvm::dyn_cast<Array>(rcref.get()); if (array == nullptr) { return absl::InvalidArgumentError( absl::Substitute("Array at $0 supplied to RemapArrays() is " "not a xla::ifrt::proxy::Array.", rcref.get())); } req->add_array_handles(array->handle_.handle); } TF_ASSIGN_OR_RETURN(std::shared_ptr<RemapArraysResponse> response, rpc_helper->RemapArrays(std::move(req)).Await()); std::vector<ArrayHandle> handles; for (auto& handle : response->array_handles()) { handles.push_back(ArrayHandle{handle}); } TF_RET_CHECK(handles.size() == plan.output_specs.size()); std::vector<tsl::RCReference<xla::ifrt::Array>> result; result.reserve(handles.size()); for (int i = 0; i < handles.size(); ++i) { result.push_back(tsl::RCReference<xla::ifrt::Array>( tsl::MakeRef<Array>(client, rpc_helper, plan.output_specs[i].dtype, plan.output_specs[i].shape, plan.output_specs[i].sharding, handles[i]))); } return result; } Array::DisassembleIntoSingleDeviceArrays(ArrayCopySemantics semantics) { auto req = std::make_unique<DisassembleIntoSingleDeviceArraysRequest>(); req->set_array_handle(handle_.handle); req->set_copy_semantics(ToArrayCopySemanticsProto(semantics)); TF_ASSIGN_OR_RETURN( std::shared_ptr<DisassembleIntoSingleDeviceArraysResponse> response, rpc_helper_->DisassembleIntoSingleDeviceArrays(std::move(req)).Await()); std::vector<ArrayHandle> handles; for (auto& handle : response->single_device_array_handles()) { handles.push_back(ArrayHandle{handle}); } TF_ASSIGN_OR_RETURN(auto shape_and_shardings, sharding_->Disassemble(shape_)); CHECK_EQ(handles.size(), shape_and_shardings.size()) << " " << absl::StrJoin(handles, ",") << " " << shape_ << " " << *sharding_ << " "; std::vector<tsl::RCReference<xla::ifrt::Array>> result; result.reserve(handles.size()); for (int i = 0; i < handles.size(); ++i) { result.push_back(tsl::RCReference<xla::ifrt::Array>(tsl::MakeRef<Array>( client_, rpc_helper_, dtype_, std::move(shape_and_shardings[i].first), std::move(shape_and_shardings[i].second), handles[i]))); } return result; } absl::StatusOr<tsl::RCReference<xla::ifrt::Array>> Array::FullyReplicatedShard( ArrayCopySemantics semantics) { auto req = std::make_unique<FullyReplicatedShardRequest>(); req->set_array_handle(handle_.handle); req->set_copy_semantics(ToArrayCopySemanticsProto(semantics)); TF_ASSIGN_OR_RETURN( std::shared_ptr<FullyReplicatedShardResponse> response, rpc_helper_->FullyReplicatedShard(std::move(req)).Await()); ArrayHandle handle{response->array_handle()}; // We are making the assumption the Array returned by the server corresponds // to the first device. Revisit this when IFRT supports: (1) an inexpensive // way to derive a SingleDeviceSharding from a fully replicated Array's // sharding and (2) A generalized `Reshard` API that allows the user to // request an Array to be made out of a specific single shard. std::unique_ptr<xla::ifrt::SingleDeviceSharding> single_device_sharding = xla::ifrt::SingleDeviceSharding::Create(sharding_->devices()[0], sharding_->memory_kind()); return tsl::RCReference<xla::ifrt::Array>( tsl::MakeRef<Array>(client_, rpc_helper_, dtype_, shape_, std::move(single_device_sharding), handle)); } absl::StatusOr<tsl::RCReference<xla::ifrt::Array>> Array::Reshard( std::shared_ptr<const Sharding> new_sharding, ArrayCopySemantics semantics) { auto req = std::make_unique<ReshardRequest>(); req->set_array_handle(handle_.handle); TF_ASSIGN_OR_RETURN(*req->mutable_sharding(), new_sharding->ToProto()); req->set_copy_semantics(ToArrayCopySemanticsProto(semantics)); TF_ASSIGN_OR_RETURN(std::shared_ptr<ReshardResponse> response, rpc_helper_->Reshard(std::move(req)).Await()); ArrayHandle handle{response->array_handle()}; return tsl::RCReference<xla::ifrt::Array>(tsl::MakeRef<Array>( client_, rpc_helper_, dtype_, shape_, std::move(new_sharding), handle)); } Future<> Array::CopyToHostBuffer( void* data, std::optional<absl::Span<const int64_t>> byte_strides, ArrayCopySemantics semantics) { const auto mem_region = ArrayMemRegion::FromZerothElementPointer( /*zeroth_element=*/data, dtype_, shape_, byte_strides); if (!mem_region.ok()) { return Future<>(mem_region.status()); } auto req = std::make_unique<CopyToHostBufferRequest>(); req->set_array_handle(handle_.handle); if (byte_strides.has_value()) { *req->mutable_byte_strides() = ToByteStridesProto(*byte_strides); } const uint64_t host_buffer_handle = rpc_helper_->host_buffer_store()->NextHandle(); req->set_host_buffer_handle(host_buffer_handle); auto promise = Future<>::CreatePromise(); auto on_ready = [host_buffer_store = rpc_helper_->host_buffer_store(), promise, host_buffer_handle, mem_region = mem_region->mem_region()]( absl::StatusOr<std::shared_ptr<CopyToHostBufferResponse>> resp) mutable { if (!resp.ok()) { promise.Set(resp.status()); return; } auto host_buffer = host_buffer_store->Lookup(host_buffer_handle); host_buffer.OnReady( [promise, mem_region, host_buffer_store, host_buffer_handle](absl::StatusOr<absl::Cord> data) mutable { absl::Cleanup cleanup = [&]() { host_buffer_store->Delete(host_buffer_handle) .OnReady([buffer_status = data.status()](absl::Status status) { if (!status.ok()) { LOG(WARNING) << "Failed to delete host buffer: " << status << " (buffer status: " << buffer_status << ")"; } }); }; if (!data.ok()) { promise.Set(data.status()); return; } if (data->size() != mem_region.size()) { auto status = absl::InternalError( absl::StrCat("During CopyToHostBuffer, size mismatch in " "response from proxy: ", mem_region.size(), " vs ", data->size())); LOG(ERROR) << status; promise.Set(status); return; } #if defined(PLATFORM_GOOGLE) data->CopyToArray(const_cast<char*>(mem_region.data())); #else std::memcpy(const_cast<char*>(mem_region.data()), data->Flatten().data(), data->size()); #endif promise.Set(); }); }; rpc_helper_->CopyToHostBuffer(std::move(req)).OnReady(std::move(on_ready)); return Future<>(std::move(promise)); } auto on_ready = [host_buffer_store = rpc_helper_->host_buffer_store(), promise, host_buffer_handle, mem_region = mem_region->mem_region()]( absl::StatusOr<std::shared_ptr<CopyToHostBufferResponse>> resp) mutable { if (!resp.ok()) { promise.Set(resp.status()); return; } auto host_buffer = host_buffer_store->Lookup(host_buffer_handle); host_buffer.OnReady( [promise, mem_region, host_buffer_store, host_buffer_handle](absl::StatusOr<absl::Cord> data) mutable { absl::Cleanup cleanup = [&]() { host_buffer_store->Delete(host_buffer_handle) .OnReady([buffer_status = data.status()](absl::Status status) { if (!status.ok()) { LOG(WARNING) << "Failed to delete host buffer: " << status << " (buffer status: " << buffer_status << ")"; } }); }; if (!data.ok()) { promise.Set(data.status()); return; } if (data->size() != mem_region.size()) { auto status = absl::InternalError( absl::StrCat("During CopyToHostBuffer, size mismatch in " "response from proxy: ", mem_region.size(), " vs ", data->size())); LOG(ERROR) << status; promise.Set(status); return; } #if defined(PLATFORM_GOOGLE) data->CopyToArray(const_cast<char*>(mem_region.data())); #else std::memcpy(const_cast<char*>(mem_region.data()), data->Flatten().data(), data->size()); #endif promise.Set(); }); }; [promise, mem_region, host_buffer_store, host_buffer_handle](absl::StatusOr<absl::Cord> data) mutable { absl::Cleanup cleanup = [&]() { host_buffer_store->Delete(host_buffer_handle) .OnReady([buffer_status = data.status()](absl::Status status) { if (!status.ok()) { LOG(WARNING) << "Failed to delete host buffer: " << status << " (buffer status: " << buffer_status << ")"; } }); }; if (!data.ok()) { promise.Set(data.status()); return; } if (data->size() != mem_region.size()) { auto status = absl::InternalError( absl::StrCat("During CopyToHostBuffer, size mismatch in " "response from proxy: ", mem_region.size(), " vs ", data->size())); LOG(ERROR) << status; promise.Set(status); return; } #if defined(PLATFORM_GOOGLE) data->CopyToArray(const_cast<char*>(mem_region.data())); #else std::memcpy(const_cast<char*>(mem_region.data()), data->Flatten().data(), data->size()); #endif promise.Set(); }); absl::Cleanup cleanup = [&]() { host_buffer_store->Delete(host_buffer_handle) .OnReady([buffer_status = data.status()](absl::Status status) { if (!status.ok()) { LOG(WARNING) << "Failed to delete host buffer: " << status << " (buffer status: " << buffer_status << ")"; } }); }; .OnReady([buffer_status = data.status()](absl::Status status) { if (!status.ok()) { LOG(WARNING) << "Failed to delete host buffer: " << status << " (buffer status: " << buffer_status << ")"; } }); xla::ifrt::Client* Array::client() const { return client_; } std::string Array::DebugString() const { return absl::Substitute("proxy::Array, this=$0, handle=$1", this, handle_.handle); }
#include "xla/python/ifrt_proxy/client/array.h" #include <memory> #include <utility> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/status/status.h" #include "absl/types/span.h" #include "xla/python/ifrt/array.h" #include "xla/python/ifrt/dtype.h" #include "xla/python/ifrt/future.h" #include "xla/python/ifrt/memory.h" #include "xla/python/ifrt/mock.h" #include "xla/python/ifrt/shape.h" #include "xla/python/ifrt/sharding.h" #include "xla/python/ifrt_proxy/client/client_session.h" #include "xla/python/ifrt_proxy/client/host_buffer.h" #include "xla/python/ifrt_proxy/client/mock_client_session.h" #include "xla/python/ifrt_proxy/client/mock_host_buffer.h" #include "xla/python/ifrt_proxy/client/rpc_helper.h" #include "xla/python/ifrt_proxy/client/version.h" #include "xla/python/ifrt_proxy/common/ifrt_service.pb.h" #include "xla/python/ifrt_proxy/common/types.h" #include "xla/python/ifrt_proxy/common/types.pb.h" #include "xla/tsl/concurrency/ref_count.h" #include "tsl/platform/protobuf.h" // IWYU pragma: keep #include "tsl/platform/status_matchers.h" #include "tsl/platform/test.h" class ArrayTest : public ::testing::Test { protected: void SetUp() override { session_ = std::make_shared<MockClientSession>(); rpc_helper_ = std::make_shared<RpcHelper>(Version(), session_); host_buffer_store_ = std::make_shared<MockClientHostBufferStore>(); rpc_helper_->set_host_buffer_store(host_buffer_store_); // Default handler that ignores all uninteresting requests, but still // invokes the callback in order to avoid hanging the caller forever. EXPECT_CALL(*session_, Enqueue(_)) .WillRepeatedly(Return(Future<ClientSession::Response>( absl::InternalError("Request has no mock handlers")))); } std::shared_ptr<MockClientSession> session_; std::shared_ptr<RpcHelper> rpc_helper_; std::shared_ptr<ClientHostBufferStore> host_buffer_store_; }; TEST_F(ArrayTest, Destruction) { IfrtResponse response; EXPECT_CALL( *session_, Enqueue(Pointee(Partially(EquivToProto(R"pb(destruct_array_request { array_handle: 1234 })pb"))))) .WillOnce(MockClientSessionReturnResponse(response)); MockClient client; tsl::MakeRef<Array>(&client, rpc_helper_, DType(DType::Kind::kBF16), Shape({}), /*sharding=*/nullptr, ArrayHandle{1234}); }
ArrayTest_FullyReplicatedShard
xla/python/ifrt_proxy/client/array_test.cc
Array::MakeArrayFromHostBuffer( xla::ifrt::Client* client, std::shared_ptr<RpcHelper> rpc_helper, const void* data, DType dtype, Shape shape, std::optional<absl::Span<const int64_t>> byte_strides, std::shared_ptr<const Sharding> sharding, xla::ifrt::Client::HostBufferSemantics semantics, std::function<void()> on_done_with_host_buffer) { TF_ASSIGN_OR_RETURN(const auto array_mem_region, ArrayMemRegion::FromZerothElementPointer( /*zeroth_element=*/data, dtype, shape, byte_strides)); const uint64_t host_buffer_handle = rpc_helper->host_buffer_store()->NextHandle(); TF_RETURN_IF_ERROR( rpc_helper->host_buffer_store() ->Store(host_buffer_handle, array_mem_region.mem_region()) .Await()); auto req = std::make_unique<MakeArrayFromHostBufferRequest>(); req->set_host_buffer_handle(host_buffer_handle); *req->mutable_dtype() = dtype.ToProto(); *req->mutable_shape() = shape.ToProto(); TF_ASSIGN_OR_RETURN(*req->mutable_sharding(), sharding->ToProto()); if (byte_strides.has_value()) { *req->mutable_byte_strides() = ToByteStridesProto(*byte_strides); } TF_ASSIGN_OR_RETURN( auto response, rpc_helper->MakeArrayFromHostBuffer(std::move(req)).Await()); const ArrayHandle handle{response->array_handle()}; if (on_done_with_host_buffer != nullptr) { std::move(on_done_with_host_buffer)(); } return tsl::RCReference<xla::ifrt::Array>( tsl::MakeRef<Array>(client, std::move(rpc_helper), dtype, std::move(shape), std::move(sharding), handle)); } void Array::Destruct(RpcHelper* rpc_helper, ArrayHandle handle) { auto req = std::make_unique<DestructArrayRequest>(); req->set_array_handle(handle.handle); rpc_helper->DestructArray(std::move(req)) .OnReady( [](absl::StatusOr<std::shared_ptr<DestructArrayResponse>> response) { if (!response.ok()) { LOG(WARNING) << "Server returned an error when asked to destruct array: " << response.status(); } }); } [](absl::StatusOr<std::shared_ptr<DestructArrayResponse>> response) { if (!response.ok()) { LOG(WARNING) << "Server returned an error when asked to destruct array: " << response.status(); } }); Future<> Array::GetReadyFuture() const { auto req = std::make_unique<CheckValueReadyRequest>(); req->add_value_handles(handle_.handle); auto promise = Future<>::CreatePromise(); rpc_helper_->CheckValueReady(std::move(req)) .OnReady( [promise](absl::StatusOr<std::shared_ptr<CheckValueReadyResponse>> resp) mutable { promise.Set(resp.status()); }); return Future<>(std::move(promise)); } [promise](absl::StatusOr<std::shared_ptr<CheckValueReadyResponse>> resp) mutable { promise.Set(resp.status()); }); Future<> Array::Delete() { auto req = std::make_unique<DeleteArrayRequest>(); req->set_array_handle(handle_.handle); absl::StatusOr<std::shared_ptr<DeleteArrayResponse>> response = rpc_helper_->DeleteArray(std::move(req)).Await(); if (!response.ok()) { return Future<>(response.status()); } // TODO(b/266635130): So that the caller is not blocked until the server // replies with the deletion's response, from within // `Future(status_handle_promise).OnReady()`, schedule `CheckFuture()` on a // separate thread. return rpc_helper_->CheckFuture((*response)->deletion_future_handle()); } bool Array::IsDeleted() const { auto req = std::make_unique<IsArrayDeletedRequest>(); req->set_array_handle(handle_.handle); absl::StatusOr<std::shared_ptr<IsArrayDeletedResponse>> response = rpc_helper_->IsArrayDeleted(std::move(req)).Await(); if (response.ok()) { return (*response)->deleted(); } else { LOG(ERROR) << "Internal error from proxy server during Array::IsDeleted(): " << response.status(); // Return false so that the user likely queries the array with some // method that returns an absl::Status, and ends up with the real // error being returned to them by that method. return false; } } Array::AssembleArrayFromSingleDeviceArrays( xla::ifrt::Client* client, std::shared_ptr<RpcHelper> rpc_helper, Shape shape, std::shared_ptr<const Sharding> sharding, absl::Span<tsl::RCReference<xla::ifrt::Array>> arrays, ArrayCopySemantics semantics) { auto req = std::make_unique<AssembleArrayFromSingleDeviceArraysRequest>(); TF_RET_CHECK(!arrays.empty()); *req->mutable_shape() = shape.ToProto(); TF_ASSIGN_OR_RETURN(*req->mutable_sharding(), sharding->ToProto()); req->set_copy_semantics(ToArrayCopySemanticsProto(semantics)); for (const tsl::RCReference<xla::ifrt::Array>& rcref : arrays) { Array* array = llvm::dyn_cast<Array>(rcref.get()); if (array == nullptr) { return absl::InvalidArgumentError(absl::Substitute( "Array at $0 supplied to AssembleArrayFromSingleDeviceArrays() is " "not a xla::ifrt::proxy::Array.", rcref.get())); } req->add_single_device_array_handles(array->handle_.handle); } TF_ASSIGN_OR_RETURN( std::shared_ptr<AssembleArrayFromSingleDeviceArraysResponse> response, rpc_helper->AssembleArrayFromSingleDeviceArrays(std::move(req)).Await()); ArrayHandle handle{response->array_handle()}; return tsl::RCReference<xla::ifrt::Array>( tsl::MakeRef<Array>(client, std::move(rpc_helper), arrays[0]->dtype(), std::move(shape), std::move(sharding), handle)); } Array::RemapArrays(xla::ifrt::Client* client, std::shared_ptr<RpcHelper> rpc_helper, const RemapPlan& plan, absl::Span<tsl::RCReference<xla::ifrt::Array>> arrays, ArrayCopySemantics semantics) { auto req = std::make_unique<RemapArraysRequest>(); TF_RET_CHECK(!arrays.empty()); TF_ASSIGN_OR_RETURN(*req->mutable_plan(), plan.ToProto()); req->set_copy_semantics(ToArrayCopySemanticsProto(semantics)); for (const tsl::RCReference<xla::ifrt::Array>& rcref : arrays) { Array* array = llvm::dyn_cast<Array>(rcref.get()); if (array == nullptr) { return absl::InvalidArgumentError( absl::Substitute("Array at $0 supplied to RemapArrays() is " "not a xla::ifrt::proxy::Array.", rcref.get())); } req->add_array_handles(array->handle_.handle); } TF_ASSIGN_OR_RETURN(std::shared_ptr<RemapArraysResponse> response, rpc_helper->RemapArrays(std::move(req)).Await()); std::vector<ArrayHandle> handles; for (auto& handle : response->array_handles()) { handles.push_back(ArrayHandle{handle}); } TF_RET_CHECK(handles.size() == plan.output_specs.size()); std::vector<tsl::RCReference<xla::ifrt::Array>> result; result.reserve(handles.size()); for (int i = 0; i < handles.size(); ++i) { result.push_back(tsl::RCReference<xla::ifrt::Array>( tsl::MakeRef<Array>(client, rpc_helper, plan.output_specs[i].dtype, plan.output_specs[i].shape, plan.output_specs[i].sharding, handles[i]))); } return result; } Array::DisassembleIntoSingleDeviceArrays(ArrayCopySemantics semantics) { auto req = std::make_unique<DisassembleIntoSingleDeviceArraysRequest>(); req->set_array_handle(handle_.handle); req->set_copy_semantics(ToArrayCopySemanticsProto(semantics)); TF_ASSIGN_OR_RETURN( std::shared_ptr<DisassembleIntoSingleDeviceArraysResponse> response, rpc_helper_->DisassembleIntoSingleDeviceArrays(std::move(req)).Await()); std::vector<ArrayHandle> handles; for (auto& handle : response->single_device_array_handles()) { handles.push_back(ArrayHandle{handle}); } TF_ASSIGN_OR_RETURN(auto shape_and_shardings, sharding_->Disassemble(shape_)); CHECK_EQ(handles.size(), shape_and_shardings.size()) << " " << absl::StrJoin(handles, ",") << " " << shape_ << " " << *sharding_ << " "; std::vector<tsl::RCReference<xla::ifrt::Array>> result; result.reserve(handles.size()); for (int i = 0; i < handles.size(); ++i) { result.push_back(tsl::RCReference<xla::ifrt::Array>(tsl::MakeRef<Array>( client_, rpc_helper_, dtype_, std::move(shape_and_shardings[i].first), std::move(shape_and_shardings[i].second), handles[i]))); } return result; } absl::StatusOr<tsl::RCReference<xla::ifrt::Array>> Array::FullyReplicatedShard( ArrayCopySemantics semantics) { auto req = std::make_unique<FullyReplicatedShardRequest>(); req->set_array_handle(handle_.handle); req->set_copy_semantics(ToArrayCopySemanticsProto(semantics)); TF_ASSIGN_OR_RETURN( std::shared_ptr<FullyReplicatedShardResponse> response, rpc_helper_->FullyReplicatedShard(std::move(req)).Await()); ArrayHandle handle{response->array_handle()}; // We are making the assumption the Array returned by the server corresponds // to the first device. Revisit this when IFRT supports: (1) an inexpensive // way to derive a SingleDeviceSharding from a fully replicated Array's // sharding and (2) A generalized `Reshard` API that allows the user to // request an Array to be made out of a specific single shard. std::unique_ptr<xla::ifrt::SingleDeviceSharding> single_device_sharding = xla::ifrt::SingleDeviceSharding::Create(sharding_->devices()[0], sharding_->memory_kind()); return tsl::RCReference<xla::ifrt::Array>( tsl::MakeRef<Array>(client_, rpc_helper_, dtype_, shape_, std::move(single_device_sharding), handle)); } absl::StatusOr<tsl::RCReference<xla::ifrt::Array>> Array::Reshard( std::shared_ptr<const Sharding> new_sharding, ArrayCopySemantics semantics) { auto req = std::make_unique<ReshardRequest>(); req->set_array_handle(handle_.handle); TF_ASSIGN_OR_RETURN(*req->mutable_sharding(), new_sharding->ToProto()); req->set_copy_semantics(ToArrayCopySemanticsProto(semantics)); TF_ASSIGN_OR_RETURN(std::shared_ptr<ReshardResponse> response, rpc_helper_->Reshard(std::move(req)).Await()); ArrayHandle handle{response->array_handle()}; return tsl::RCReference<xla::ifrt::Array>(tsl::MakeRef<Array>( client_, rpc_helper_, dtype_, shape_, std::move(new_sharding), handle)); } Future<> Array::CopyToHostBuffer( void* data, std::optional<absl::Span<const int64_t>> byte_strides, ArrayCopySemantics semantics) { const auto mem_region = ArrayMemRegion::FromZerothElementPointer( /*zeroth_element=*/data, dtype_, shape_, byte_strides); if (!mem_region.ok()) { return Future<>(mem_region.status()); } auto req = std::make_unique<CopyToHostBufferRequest>(); req->set_array_handle(handle_.handle); if (byte_strides.has_value()) { *req->mutable_byte_strides() = ToByteStridesProto(*byte_strides); } const uint64_t host_buffer_handle = rpc_helper_->host_buffer_store()->NextHandle(); req->set_host_buffer_handle(host_buffer_handle); auto promise = Future<>::CreatePromise(); auto on_ready = [host_buffer_store = rpc_helper_->host_buffer_store(), promise, host_buffer_handle, mem_region = mem_region->mem_region()]( absl::StatusOr<std::shared_ptr<CopyToHostBufferResponse>> resp) mutable { if (!resp.ok()) { promise.Set(resp.status()); return; } auto host_buffer = host_buffer_store->Lookup(host_buffer_handle); host_buffer.OnReady( [promise, mem_region, host_buffer_store, host_buffer_handle](absl::StatusOr<absl::Cord> data) mutable { absl::Cleanup cleanup = [&]() { host_buffer_store->Delete(host_buffer_handle) .OnReady([buffer_status = data.status()](absl::Status status) { if (!status.ok()) { LOG(WARNING) << "Failed to delete host buffer: " << status << " (buffer status: " << buffer_status << ")"; } }); }; if (!data.ok()) { promise.Set(data.status()); return; } if (data->size() != mem_region.size()) { auto status = absl::InternalError( absl::StrCat("During CopyToHostBuffer, size mismatch in " "response from proxy: ", mem_region.size(), " vs ", data->size())); LOG(ERROR) << status; promise.Set(status); return; } #if defined(PLATFORM_GOOGLE) data->CopyToArray(const_cast<char*>(mem_region.data())); #else std::memcpy(const_cast<char*>(mem_region.data()), data->Flatten().data(), data->size()); #endif promise.Set(); }); }; rpc_helper_->CopyToHostBuffer(std::move(req)).OnReady(std::move(on_ready)); return Future<>(std::move(promise)); } auto on_ready = [host_buffer_store = rpc_helper_->host_buffer_store(), promise, host_buffer_handle, mem_region = mem_region->mem_region()]( absl::StatusOr<std::shared_ptr<CopyToHostBufferResponse>> resp) mutable { if (!resp.ok()) { promise.Set(resp.status()); return; } auto host_buffer = host_buffer_store->Lookup(host_buffer_handle); host_buffer.OnReady( [promise, mem_region, host_buffer_store, host_buffer_handle](absl::StatusOr<absl::Cord> data) mutable { absl::Cleanup cleanup = [&]() { host_buffer_store->Delete(host_buffer_handle) .OnReady([buffer_status = data.status()](absl::Status status) { if (!status.ok()) { LOG(WARNING) << "Failed to delete host buffer: " << status << " (buffer status: " << buffer_status << ")"; } }); }; if (!data.ok()) { promise.Set(data.status()); return; } if (data->size() != mem_region.size()) { auto status = absl::InternalError( absl::StrCat("During CopyToHostBuffer, size mismatch in " "response from proxy: ", mem_region.size(), " vs ", data->size())); LOG(ERROR) << status; promise.Set(status); return; } #if defined(PLATFORM_GOOGLE) data->CopyToArray(const_cast<char*>(mem_region.data())); #else std::memcpy(const_cast<char*>(mem_region.data()), data->Flatten().data(), data->size()); #endif promise.Set(); }); }; [promise, mem_region, host_buffer_store, host_buffer_handle](absl::StatusOr<absl::Cord> data) mutable { absl::Cleanup cleanup = [&]() { host_buffer_store->Delete(host_buffer_handle) .OnReady([buffer_status = data.status()](absl::Status status) { if (!status.ok()) { LOG(WARNING) << "Failed to delete host buffer: " << status << " (buffer status: " << buffer_status << ")"; } }); }; if (!data.ok()) { promise.Set(data.status()); return; } if (data->size() != mem_region.size()) { auto status = absl::InternalError( absl::StrCat("During CopyToHostBuffer, size mismatch in " "response from proxy: ", mem_region.size(), " vs ", data->size())); LOG(ERROR) << status; promise.Set(status); return; } #if defined(PLATFORM_GOOGLE) data->CopyToArray(const_cast<char*>(mem_region.data())); #else std::memcpy(const_cast<char*>(mem_region.data()), data->Flatten().data(), data->size()); #endif promise.Set(); }); absl::Cleanup cleanup = [&]() { host_buffer_store->Delete(host_buffer_handle) .OnReady([buffer_status = data.status()](absl::Status status) { if (!status.ok()) { LOG(WARNING) << "Failed to delete host buffer: " << status << " (buffer status: " << buffer_status << ")"; } }); }; .OnReady([buffer_status = data.status()](absl::Status status) { if (!status.ok()) { LOG(WARNING) << "Failed to delete host buffer: " << status << " (buffer status: " << buffer_status << ")"; } }); xla::ifrt::Client* Array::client() const { return client_; } std::string Array::DebugString() const { return absl::Substitute("proxy::Array, this=$0, handle=$1", this, handle_.handle); }
#include "xla/python/ifrt_proxy/client/array.h" #include <memory> #include <utility> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/status/status.h" #include "absl/types/span.h" #include "xla/python/ifrt/array.h" #include "xla/python/ifrt/dtype.h" #include "xla/python/ifrt/future.h" #include "xla/python/ifrt/memory.h" #include "xla/python/ifrt/mock.h" #include "xla/python/ifrt/shape.h" #include "xla/python/ifrt/sharding.h" #include "xla/python/ifrt_proxy/client/client_session.h" #include "xla/python/ifrt_proxy/client/host_buffer.h" #include "xla/python/ifrt_proxy/client/mock_client_session.h" #include "xla/python/ifrt_proxy/client/mock_host_buffer.h" #include "xla/python/ifrt_proxy/client/rpc_helper.h" #include "xla/python/ifrt_proxy/client/version.h" #include "xla/python/ifrt_proxy/common/ifrt_service.pb.h" #include "xla/python/ifrt_proxy/common/types.h" #include "xla/python/ifrt_proxy/common/types.pb.h" #include "xla/tsl/concurrency/ref_count.h" #include "tsl/platform/protobuf.h" // IWYU pragma: keep #include "tsl/platform/status_matchers.h" #include "tsl/platform/test.h" class ArrayTest : public ::testing::Test { protected: void SetUp() override { session_ = std::make_shared<MockClientSession>(); rpc_helper_ = std::make_shared<RpcHelper>(Version(), session_); host_buffer_store_ = std::make_shared<MockClientHostBufferStore>(); rpc_helper_->set_host_buffer_store(host_buffer_store_); // Default handler that ignores all uninteresting requests, but still // invokes the callback in order to avoid hanging the caller forever. EXPECT_CALL(*session_, Enqueue(_)) .WillRepeatedly(Return(Future<ClientSession::Response>( absl::InternalError("Request has no mock handlers")))); } std::shared_ptr<MockClientSession> session_; std::shared_ptr<RpcHelper> rpc_helper_; std::shared_ptr<ClientHostBufferStore> host_buffer_store_; }; TEST_F(ArrayTest, FullyReplicatedShard) { IfrtResponse response; ASSERT_TRUE(TextFormat::ParseFromString( R"pb(response_metadata {} fully_replicated_shard_response { array_handle: 5678 })pb", &response)); EXPECT_CALL(*session_, Enqueue(Pointee(Partially(EquivToProto( R"pb(fully_replicated_shard_request { array_handle: 1234 })pb"))))) .WillOnce(MockClientSessionReturnResponse(response)); MockClient client; MockDevice mock_device; auto sharding = xla::ifrt::SingleDeviceSharding::Create( &mock_device, xla::ifrt::MemoryKind()); auto array = tsl::MakeRef<Array>(&client, rpc_helper_, DType(DType::Kind::kBF16), Shape({}), std::move(sharding), ArrayHandle{1234}); ASSERT_THAT(array->FullyReplicatedShard(ArrayCopySemantics::kAlwaysCopy), IsOk()); }
CompilerTest_Compile
xla/python/ifrt_proxy/client/compiler_test.cc
Compiler::Compiler(xla::ifrt::Client* client, std::shared_ptr<RpcHelper> rpc_helper) : client_(client), rpc_helper_(std::move(rpc_helper)) {} absl::StatusOr<std::unique_ptr<xla::ifrt::LoadedExecutable>> Compiler::Compile( std::unique_ptr<Program> program, std::unique_ptr<xla::ifrt::CompileOptions> options) { auto request = std::make_unique<CompileRequest>(); TF_ASSIGN_OR_RETURN(*request->mutable_program(), Serialize(*program)); // Extract host callbacks from the XLA compile options. `XlaCompileOptions`'s // SerDes fails when it contains host callbacks, so the following // implementation handles host callback serialization out of band until we can // natively support IFRT host callback on IFRT proxy. std::vector<tsl::RCReference<xla::ifrt::LoadedHostCallback>> loaded_host_callbacks; if (auto* xla_options = llvm::dyn_cast<xla::ifrt::XlaCompileOptions>(options.get())) { for (const auto& loaded_host_callback : xla_options->loaded_host_callbacks) { auto* pjrt_host_callback = llvm::dyn_cast<xla::ifrt::PjRtHostSendAndRecvLoadedHostCallback>( loaded_host_callback.get()); if (pjrt_host_callback == nullptr) { return absl::UnimplementedError("Unsupported host callback type"); } const xla::HostCallback& xla_host_callback = pjrt_host_callback->host_callback(); // The proxy server runs `RemoteLoadedHostCallback` that delegates actual // host callback execution to the proxy client. auto remote_loaded_host_callback = tsl::MakeRef<RemoteLoadedHostCallback>( client_, xla_host_callback.operands, xla_host_callback.results, /*queue=*/nullptr); TF_ASSIGN_OR_RETURN(*request->add_host_callbacks(), remote_loaded_host_callback->Serialize()); } loaded_host_callbacks.swap(xla_options->loaded_host_callbacks); } TF_ASSIGN_OR_RETURN(*request->mutable_compile_options(), Serialize(*options)); // TODO(b/266635130): Avoid blocking the caller. TF_ASSIGN_OR_RETURN(std::shared_ptr<CompileResponse> response, rpc_helper_->Compile(std::move(request)).Await()); std::vector<xla::ifrt::LoadedExecutable::LogicalDeviceIds> addressable_device_logical_device_ids; addressable_device_logical_device_ids.reserve( response->addressable_device_logical_ids_size()); for (const auto& logical_device_id : response->addressable_device_logical_ids()) { xla::ifrt::LoadedExecutable::LogicalDeviceIds id{ logical_device_id.replica(), logical_device_id.partition()}; addressable_device_logical_device_ids.push_back(id); } std::vector<xla::ifrt::Device*> addressable_devices; addressable_devices.reserve(response->addressable_device_ids_size()); for (const int32_t device_id : response->addressable_device_ids()) { TF_ASSIGN_OR_RETURN(xla::ifrt::Device* const device, client_->LookupDevice(DeviceId(device_id))); addressable_devices.push_back(device); } absl::StatusOr<std::optional<std::string>> fingerprint; switch (response->fingerprint_case()) { case CompileResponse::kFingerprintValue: fingerprint = response->fingerprint_value(); break; case CompileResponse::kFingerprintError: fingerprint = tsl::StatusFromProto(response->fingerprint_error()); break; default: fingerprint = std::nullopt; break; } Future<> ready_future = rpc_helper_->CheckFuture(response->ready_future_handle()); std::vector<uint64_t> loaded_host_callback_handles( response->loaded_host_callback_handles().begin(), response->loaded_host_callback_handles().end()); return std::make_unique<LoadedExecutable>( client_, rpc_helper_, response->loaded_executable_handle(), response->name(), response->num_devices(), std::move(addressable_device_logical_device_ids), std::move(addressable_devices), std::move(fingerprint), std::move(ready_future), std::move(loaded_host_callbacks), std::move(loaded_host_callback_handles)); } absl::StatusOr<std::unique_ptr<Executable>> Compiler::Compile( std::unique_ptr<Program> program, const Topology& topology, std::unique_ptr<CompileOptions> options) { return absl::UnimplementedError( "IFRT service compiler does not support `Compile` with a topology"); } Compiler::DeserializeLoadedExecutable( absl::string_view serialized, std::unique_ptr<xla::ifrt::DeserializeExecutableOptions> options) { return absl::UnimplementedError( "IFRT service compiler does not support `DeserializeLoadedExecutable` " "since the underlying serialization format is not stable"); }
#include "xla/python/ifrt_proxy/client/compiler.h" #include <memory> #include <string> #include <vector> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "llvm/Support/Casting.h" #include "llvm/Support/ExtensibleRTTI.h" #include "xla/python/ifrt/compiler.h" #include "xla/python/ifrt/future.h" #include "xla/python/ifrt/mock.h" #include "xla/python/ifrt/serdes.h" #include "xla/python/ifrt_proxy/client/client_session.h" #include "xla/python/ifrt_proxy/client/host_buffer.h" #include "xla/python/ifrt_proxy/client/mock_client_session.h" #include "xla/python/ifrt_proxy/client/mock_host_buffer.h" #include "xla/python/ifrt_proxy/client/rpc_helper.h" #include "xla/python/ifrt_proxy/client/version.h" #include "xla/python/ifrt_proxy/common/ifrt_service.pb.h" #include "tsl/platform/protobuf.h" // IWYU pragma: keep #include "tsl/platform/status_matchers.h" #include "tsl/platform/statusor.h" #include "tsl/platform/test.h" class CompilerTest : public testing::Test { protected: static void SetUpTestSuite() { RegisterSerDes<TestProgram>(std::make_unique<TestProgramSerDes>()); RegisterSerDes<TestCompileOptions>( std::make_unique<TestCompileOptionsSerDes>()); } void SetUp() override { session_ = std::make_shared<MockClientSession>(); rpc_helper_ = std::make_shared<RpcHelper>(Version(), session_); host_buffer_store_ = std::make_shared<MockClientHostBufferStore>(); rpc_helper_->set_host_buffer_store(host_buffer_store_); // Default handler that ignores all uninteresting requests but still // invokes the callback in order to avoid hanging the caller forever. EXPECT_CALL(*session_, Enqueue(_)) .WillRepeatedly(Return(Future<ClientSession::Response>( absl::InternalError("Request has no mock handlers")))); } std::shared_ptr<MockClientSession> session_; std::shared_ptr<RpcHelper> rpc_helper_; std::shared_ptr<ClientHostBufferStore> host_buffer_store_; }; TEST_F(CompilerTest, Compile) { std::vector<MockDevice> devices(2); MockClient client; ON_CALL(client, LookupDevice(_)).WillByDefault(Invoke([&](DeviceId id) { return &devices[id.value()]; })); Compiler compiler(&client, rpc_helper_); IfrtResponse response; ASSERT_TRUE(TextFormat::ParseFromString( R"pb(compile_response { loaded_executable_handle: 1234 name: "foo-executable" num_devices: 2 addressable_device_logical_ids { replica: 0 partition: 0 } addressable_device_logical_ids { replica: 0 partition: 1 } addressable_device_ids: [ 0, 1 ] fingerprint_value: "fingerprint" ready_future_handle: 5678 })pb", &response)); EXPECT_CALL(*session_, Enqueue(Pointee(Partially(EquivToProto( R"pb(compile_request { program { type_name: "xla::ifrt::proxy::TestProgram" } })pb"))))) .WillOnce(MockClientSessionReturnResponse(response)); ASSERT_TRUE(TextFormat::ParseFromString(R"pb( response_metadata { status { code: 2 # UNKNOWN message: "injected error" } } )pb", &response)); EXPECT_CALL(*session_, Enqueue(Pointee(Partially(EquivToProto(R"pb(check_future_request { future_handle: 5678 })pb"))))) .WillOnce(MockClientSessionReturnResponse(response)); TF_ASSERT_OK_AND_ASSIGN( auto executable, compiler.Compile(std::make_unique<TestProgram>(), std::make_unique<TestCompileOptions>())); EXPECT_EQ(executable->name(), "foo-executable"); EXPECT_EQ(executable->num_devices(), 2); EXPECT_THAT(executable->addressable_device_logical_ids(), ElementsAre(FieldsAre(0, 0), FieldsAre(0, 1))); EXPECT_THAT(executable->addressable_devices(), ElementsAre(&devices[0], &devices[1])); EXPECT_THAT(executable->Fingerprint(), IsOkAndHolds(Optional(std::string("fingerprint")))); EXPECT_THAT(executable->GetReadyFuture().Await(), StatusIs(absl::StatusCode::kUnknown, "injected error")); }
CoordinationServiceAgentTest_ConnectAfterResetError
xla/tsl/distributed_runtime/coordination/coordination_service_agent_test.cc
CoordinationServiceAgentImpl() = default; ~CoordinationServiceAgentImpl() override { absl::Status s = ShutdownInternal(); VLOG(3) << "Coordination agent dtor failed with status: " << s; } VLOG(3) << "Coordination agent dtor failed with status: " << s; absl::Status CoordinationServiceAgentImpl::Initialize( Env* env, std::string_view job_name, int task_id, const CoordinationServiceConfig& configs, std::unique_ptr<CoordinationClient> leader_client, StatusCallback error_fn) { CoordinatedTask task; task.set_job_name(std::string(job_name)); task.set_task_id(task_id); return Initialize(env, task, configs, std::move(leader_client), error_fn); } absl::Status CoordinationServiceAgentImpl::Initialize( Env* env, const CoordinatedTask& task, const CoordinationServiceConfig& configs, std::unique_ptr<CoordinationClient> leader_client, StatusCallback error_fn) { enabled_usage_metric->GetCell()->Set(true); absl::MutexLock l(&state_mu_); if (state_ != CoordinatedTaskState::TASKSTATE_UNINITIALIZED) { return MakeCoordinationError(absl::FailedPreconditionError( "Coordination service agent has already been initialized.")); } env_ = env; task_ = task; configs_ = configs; if (configs_.service_leader().empty()) { return MakeCoordinationError(absl::InvalidArgumentError( "CoordinationServiceAgent must be initialized with a valid leader.")); } leader_client_ = std::move(leader_client); if (leader_client_ == nullptr) { return MakeCoordinationError(absl::InvalidArgumentError( "CoordinationServiceAgent must have a valid leader client.")); } error_fn_ = error_fn; state_ = CoordinatedTaskState::TASKSTATE_DISCONNECTED; return absl::OkStatus(); } bool CoordinationServiceAgentImpl::IsInitialized() { absl::MutexLock l(&state_mu_); return state_ != CoordinatedTaskState::TASKSTATE_UNINITIALIZED; } bool CoordinationServiceAgentImpl::IsConnected() { absl::MutexLock l(&state_mu_); return state_ == CoordinatedTaskState::TASKSTATE_CONNECTED; } bool CoordinationServiceAgentImpl::IsError() { absl::MutexLock l(&state_mu_); return state_ == CoordinatedTaskState::TASKSTATE_ERROR; } void CoordinationServiceAgentImpl::StopHeartbeat() { { absl::MutexLock l(&heartbeat_thread_shutdown_mu_); shutting_down_ = true; heartbeat_thread_cv_.SignalAll(); } heartbeat_thread_ = nullptr; } absl::Status CoordinationServiceAgentImpl::Connect() { VLOG(3) << "Agent has started trying to Connect()."; { absl::MutexLock l(&state_mu_); if (state_ != CoordinatedTaskState::TASKSTATE_DISCONNECTED) { return MakeCoordinationError(absl::FailedPreconditionError( "Coordination service agent is not in DISCONNECTED state.")); } } absl::Status connect_status = absl::UnknownError("Connection not attempted yet."); RegisterTaskRequest request; *request.mutable_source_task() = task_; request.set_incarnation(incarnation_id_); RegisterTaskResponse response; const int64_t register_timeout = configs_.cluster_register_timeout_in_ms() > 0 ? configs_.cluster_register_timeout_in_ms() : absl::ToInt64Milliseconds(kDefaultClusterRegisterTimeout); const absl::Time deadline = absl::Now() + absl::Milliseconds(register_timeout); int attempt = 0; std::default_random_engine generator; std::uniform_real_distribution<double> distribution(0.0, 1.0); do { ++attempt; CallOptions call_opts; call_opts.SetTimeout(absl::ToInt64Milliseconds(deadline - absl::Now())); absl::Notification n; leader_client_->RegisterTaskAsync( &call_opts, &request, &response, [&](absl::Status s) { if (s.ok()) { leader_incarnation_ = response.leader_incarnation(); { absl::MutexLock l(&state_mu_); state_ = CoordinatedTaskState::TASKSTATE_CONNECTED; } } connect_status = s; n.Notify(); }); n.WaitForNotification(); if (!connect_status.ok()) { // Exponential backoff with jitter. Note we will retry for `init_timeout` // time in total; the `14` here corresponds to an ~16s maximum interval // between connection attempts. const int backoff = 1 << std::min(14, attempt); absl::SleepFor(absl::Milliseconds(backoff * distribution(generator))); } } while (!connect_status.ok() && absl::Now() < deadline && // Retries are attempted for: // 1. RPC errors. // 2. aborted duplicate task registration error - this means that // this task restarted and is trying to reconnect but the service // has not restarted yet. // 3. service has not been enabled - this could happen in the single // client scenario, where the server has been started but the service // cannot be used yet (nullptr). Presumably the service is in the // process of being enabled. (connect_status.GetPayload(CoordinationErrorPayloadKey()) == std::nullopt || absl::IsAborted(connect_status) || absl::IsInternal(connect_status))); if (!connect_status.ok()) { SetError(connect_status); return connect_status; } LOG(INFO) << "Coordination agent has successfully connected."; heartbeat_thread_.reset( env_->StartThread(ThreadOptions(), kHeartbeatThread, [this]() -> void { HeartbeatRequest request; *request.mutable_source_task() = task_; request.set_incarnation(incarnation_id_); HeartbeatResponse response; const int64_t heartbeat_interval_ms = configs_.heartbeat_timeout_in_ms() > 0 ? configs_.heartbeat_timeout_in_ms() / 2 : absl::ToInt64Milliseconds(kDefaultHeartbeatTimeout) / 2; CallOptions call_opts; call_opts.SetTimeout(heartbeat_interval_ms); while (true) { absl::Status status; absl::Notification n; // Heartbeat RPC implementation automatically retries to tolerate // transient network failures. VLOG(10) << "HeartbeatRequest: " << request.DebugString(); leader_client_->HeartbeatAsync(&call_opts, &request, &response, [&](absl::Status s) { status = s; n.Notify(); }); n.WaitForNotification(); VLOG(10) << "HeartbeatResponse: " << status; if (!status.ok()) { // Ignore heartbeat errors and exit thread if shutting down. For // example, the agent may send a heartbeat right after Shutdown() // started, but before StopHeartbeat() and end of Shutdown(). This // results in an unexpected heartbeat error. // Waiting for a second allows us to identify if errors are due to // inflight heartbeats sent during shutdown and can be ignored. absl::SleepFor(absl::Seconds(1)); { absl::MutexLock l(&heartbeat_thread_shutdown_mu_); if (shutting_down_) { return; } } SetError(status); } else if (response.leader_incarnation() != leader_incarnation_) { SetError(MakeCoordinationError( absl::AbortedError("Leader incarnation ID mismatch: the " "coordination leader has restarted."))); } // Send next heartbeat after an interval. { absl::MutexLock l(&heartbeat_thread_shutdown_mu_); heartbeat_thread_cv_.WaitWithTimeout( &heartbeat_thread_shutdown_mu_, absl::Milliseconds(heartbeat_interval_ms)); if (shutting_down_) { return; } } } })); return absl::OkStatus(); } VLOG(3) << "Agent has started trying to Connect()."; &call_opts, &request, &response, [&](absl::Status s) { if (s.ok()) { leader_incarnation_ = response.leader_incarnation(); { absl::MutexLock l(&state_mu_); state_ = CoordinatedTaskState::TASKSTATE_CONNECTED; } } connect_status = s; n.Notify(); }); env_->StartThread(ThreadOptions(), kHeartbeatThread, [this]() -> void { HeartbeatRequest request; *request.mutable_source_task() = task_; request.set_incarnation(incarnation_id_); HeartbeatResponse response; const int64_t heartbeat_interval_ms = configs_.heartbeat_timeout_in_ms() > 0 ? configs_.heartbeat_timeout_in_ms() / 2 : absl::ToInt64Milliseconds(kDefaultHeartbeatTimeout) / 2; CallOptions call_opts; call_opts.SetTimeout(heartbeat_interval_ms); while (true) { absl::Status status; absl::Notification n; // Heartbeat RPC implementation automatically retries to tolerate // transient network failures. VLOG(10) << "HeartbeatRequest: " << request.DebugString(); leader_client_->HeartbeatAsync(&call_opts, &request, &response, [&](absl::Status s) { status = s; n.Notify(); }); n.WaitForNotification(); VLOG(10) << "HeartbeatResponse: " << status; if (!status.ok()) { // Ignore heartbeat errors and exit thread if shutting down. For // example, the agent may send a heartbeat right after Shutdown() // started, but before StopHeartbeat() and end of Shutdown(). This // results in an unexpected heartbeat error. // Waiting for a second allows us to identify if errors are due to // inflight heartbeats sent during shutdown and can be ignored. absl::SleepFor(absl::Seconds(1)); { absl::MutexLock l(&heartbeat_thread_shutdown_mu_); if (shutting_down_) { return; } } SetError(status); } else if (response.leader_incarnation() != leader_incarnation_) { SetError(MakeCoordinationError( absl::AbortedError("Leader incarnation ID mismatch: the " "coordination leader has restarted."))); } // Send next heartbeat after an interval. { absl::MutexLock l(&heartbeat_thread_shutdown_mu_); heartbeat_thread_cv_.WaitWithTimeout( &heartbeat_thread_shutdown_mu_, absl::Milliseconds(heartbeat_interval_ms)); if (shutting_down_) { return; } } } })); VLOG(10) << "HeartbeatRequest: " << request.DebugString(); [&](absl::Status s) { status = s; n.Notify(); }); VLOG(10) << "HeartbeatResponse: " << status; absl::Status CoordinationServiceAgentImpl::WaitForAllTasks( const DeviceInfo& local_devices) { absl::Status agent_running_status = ValidateRunningAgent(); if (!agent_running_status.ok()) { return agent_running_status; } WaitForAllTasksRequest request; *request.mutable_source_task() = task_; *request.mutable_device_info() = local_devices; VLOG(3) << "WaitForAllTasksRequest: " << request.DebugString(); WaitForAllTasksResponse response; absl::Status status; absl::Notification n; leader_client_->WaitForAllTasksAsync(&request, &response, [&](absl::Status s) { status = s; n.Notify(); }); n.WaitForNotification(); if (!status.ok()) { VLOG(3) << "WaitForAllTasksResponse: " << status; SetError(status); return status; } VLOG(3) << "WaitForAllTasksResponse: " << response.DebugString(); cluster_devices_ = response.device_info(); return absl::OkStatus(); } VLOG(3) << "WaitForAllTasksRequest: " << request.DebugString(); [&](absl::Status s) { status = s; n.Notify(); }); VLOG(3) << "WaitForAllTasksResponse: " << status; VLOG(3) << "WaitForAllTasksResponse: " << response.DebugString(); const DeviceInfo& CoordinationServiceAgentImpl::GetClusterDeviceInfo() { return cluster_devices_; } absl::StatusOr<CoordinatedTask> CoordinationServiceAgentImpl::GetOwnTask() { if (!IsInitialized()) { return MakeCoordinationError(absl::FailedPreconditionError( "Agent has not been initialized; we do not " "know the associated task yet.")); } return task_; } CoordinationServiceAgentImpl::GetTaskState( const std::vector<CoordinatedTask>& tasks) { GetTaskStateRequest request; *request.mutable_source_task() = {tasks.begin(), tasks.end()}; GetTaskStateResponse response; absl::Notification n; absl::StatusOr<std::vector<CoordinatedTaskStateInfo>> result; leader_client_->GetTaskStateAsync( &request, &response, [&](const absl::Status& s) { if (s.ok()) { result = std::vector<CoordinatedTaskStateInfo>( std::make_move_iterator(response.task_state().begin()), std::make_move_iterator(response.task_state().end())); } else { result = s; } n.Notify(); }); n.WaitForNotification(); return result; } &request, &response, [&](const absl::Status& s) { if (s.ok()) { result = std::vector<CoordinatedTaskStateInfo>( std::make_move_iterator(response.task_state().begin()), std::make_move_iterator(response.task_state().end())); } else { result = s; } n.Notify(); }); absl::Status CoordinationServiceAgentImpl::ReportError( const absl::Status& error) { { absl::MutexLock l(&state_mu_); if (state_ == CoordinatedTaskState::TASKSTATE_UNINITIALIZED) { return MakeCoordinationError(absl::FailedPreconditionError( "Coordination service agent must be initialized first before " "reporting error.")); } else if (state_ == CoordinatedTaskState::TASKSTATE_ERROR) { return MakeCoordinationError(absl::FailedPreconditionError( "Coordination service agent is already in error state.")); } } SetError(MakeCoordinationError(error, task_, /*is_reported_error=*/true)); LOG(INFO) << "Reporting error to coordination service: " << error; ReportErrorToServiceRequest request; request.set_error_code(error.raw_code()); request.set_error_message(std::string(error.message())); *request.mutable_error_origin() = task_; VLOG(5) << "ReportErrorToServiceRequest: " << request.DebugString(); ReportErrorToServiceResponse response; absl::Notification n; leader_client_->ReportErrorToServiceAsync( &request, &response, [&](absl::Status s) { VLOG(5) << "ReportErrorToServiceResponse: " << s; if (!s.ok()) { LOG(ERROR) << "Encountered another error when reporting error to " "coordination service: " << s << "\nThis is usually caused by an earlier error during " "execution. Check the logs (this task or the leader) for " "an earlier error to debug further."; } n.Notify(); }); n.WaitForNotification(); return absl::OkStatus(); } VLOG(5) << "ReportErrorToServiceRequest: " << request.DebugString(); &request, &response, [&](absl::Status s) { VLOG(5) << "ReportErrorToServiceResponse: " << s; if (!s.ok()) { LOG(ERROR) << "Encountered another error when reporting error to " "coordination service: " << s << "\nThis is usually caused by an earlier error during " "execution. Check the logs (this task or the leader) for " "an earlier error to debug further."; } n.Notify(); }); VLOG(5) << "ReportErrorToServiceResponse: " << s; absl::Status CoordinationServiceAgentImpl::Shutdown() { return ShutdownInternal(); } absl::Status CoordinationServiceAgentImpl::ShutdownInternal() { absl::Status status = absl::OkStatus(); bool is_connected = false; { absl::MutexLock l(&state_mu_); is_connected = state_ == CoordinatedTaskState::TASKSTATE_CONNECTED; } // Disconnect agent from service. if (!configs_.agent_destruction_without_shutdown() && is_connected) { LOG(INFO) << "Coordination agent has initiated Shutdown()."; ShutdownTaskRequest request; *request.mutable_source_task() = task_; ShutdownTaskResponse response; CallOptions call_opts; const int64_t shutdown_timeout = configs_.shutdown_barrier_timeout_in_ms() > 0 ? configs_.shutdown_barrier_timeout_in_ms() : absl::ToInt64Milliseconds(kDefaultShutdownTimeout); call_opts.SetTimeout(shutdown_timeout); absl::Notification n; leader_client_->ShutdownTaskAsync(&call_opts, &request, &response, [&status, &n](absl::Status s) { status = s; n.Notify(); }); n.WaitForNotification(); if (status.ok()) { LOG(INFO) << "Coordination agent has successfully shut down."; } else { LOG(ERROR) << "Failed to disconnect from coordination service with status: " << status << "\nProceeding with agent shutdown anyway. This is usually caused " "by an earlier error during execution. Check the logs (this task " "or the leader) for an earlier error to debug further."; } } // Tear down agent. StopHeartbeat(); { absl::MutexLock l(&state_mu_); if (state_ == CoordinatedTaskState::TASKSTATE_ERROR) { const std::string status_message = absl::StrCat( "Shutdown() was called while coordination agent is in error state, " "implying that distributed execution failed. Note: agent will still " "shutdown anyway. Agent status: ", status_.ToString(), "\nThis is usually caused by an earlier error during execution. " "Check the logs (this task or the leader) for an earlier error to " "debug further."); status = MakeCoordinationError(absl::FailedPreconditionError(status_message)); LOG(ERROR) << status_message; } state_ = CoordinatedTaskState::TASKSTATE_DISCONNECTED; } // Cancel all pending GetKeyValue() RPC calls. cancellation_manager_.StartCancel(); return status; } [&status, &n](absl::Status s) { status = s; n.Notify(); }); absl::Status CoordinationServiceAgentImpl::Reset() { { absl::MutexLock l(&state_mu_); if (state_ != CoordinatedTaskState::TASKSTATE_ERROR) { return MakeCoordinationError(absl::FailedPreconditionError( "Reset() failed: coordination service agent is not in ERROR state.")); } } ResetTaskRequest request; *request.mutable_source_task() = task_; VLOG(3) << "ResetTaskRequest: " << request.DebugString(); ResetTaskResponse response; absl::Status status; absl::Notification n; leader_client_->ResetTaskAsync(&request, &response, [&status, &n](absl::Status s) { status = s; n.Notify(); }); n.WaitForNotification(); VLOG(3) << "ResetTaskResponse: " << status; if (!status.ok()) { return status; } // Reset agent state. StopHeartbeat(); { absl::MutexLock l(&state_mu_); state_ = CoordinatedTaskState::TASKSTATE_DISCONNECTED; } { absl::MutexLock l(&heartbeat_thread_shutdown_mu_); shutting_down_ = false; } LOG(INFO) << "Coordination agent has been reset."; return status; } VLOG(3) << "ResetTaskRequest: " << request.DebugString(); [&status, &n](absl::Status s) { status = s; n.Notify(); }); VLOG(3) << "ResetTaskResponse: " << status; absl::StatusOr<std::string> CoordinationServiceAgentImpl::GetKeyValue( std::string_view key) { return GetKeyValue(key, /*timeout=*/absl::InfiniteDuration()); } absl::StatusOr<std::string> CoordinationServiceAgentImpl::GetKeyValue( std::string_view key, absl::Duration timeout) { auto n = std::make_shared<absl::Notification>(); auto result = std::make_shared<absl::StatusOr<std::string>>(); GetKeyValueAsync( key, [n, result](const absl::StatusOr<std::string>& status_or_value) { *result = status_or_value; n->Notify(); }); bool call_completed_before_timeout = n->WaitForNotificationWithTimeout(timeout); if (!call_completed_before_timeout) { VLOG(3) << "GetKeyValue(" << key << ") timed out after " << timeout; return MakeCoordinationError(absl::DeadlineExceededError(absl::Substitute( "GetKeyValue() timed out with key: $0 and duration: $1", key, absl::FormatDuration(timeout)))); } return *result; } key, [n, result](const absl::StatusOr<std::string>& status_or_value) { *result = status_or_value; n->Notify(); }); VLOG(3) << "GetKeyValue(" << key << ") timed out after " << timeout; std::shared_ptr<CallOptions> CoordinationServiceAgentImpl::GetKeyValueAsync( std::string_view key, StatusOrValueCallback done) { auto request = std::make_shared<GetKeyValueRequest>(); request->set_key(key.data(), key.size()); VLOG(3) << "GetKeyValueRequest: " << request->DebugString(); auto response = std::make_shared<GetKeyValueResponse>(); auto call_opts = std::make_shared<CallOptions>(); const CancellationToken token = cancellation_manager_.get_cancellation_token(); const bool already_cancelled = !cancellation_manager_.RegisterCallback( token, [call_opts]() { call_opts->StartCancel(); }); if (already_cancelled) { done(absl::CancelledError("GetKeyValueAsync() was cancelled.")); return call_opts; } leader_client_->GetKeyValueAsync( call_opts.get(), request.get(), response.get(), [call_opts, request, response, done = std::move(done), &cm = cancellation_manager_, token](const absl::Status& s) { // RPC call has completed (no longer needs to be cancelled if agent is // destroyed). cm.TryDeregisterCallback(token); // Retrieve server response. if (!s.ok()) { done(s); VLOG(3) << "GetKeyValueResponse: " << s; } else { done(response->kv().value()); VLOG(3) << "GetKeyValueResponse: " << response->DebugString(); } }); return call_opts; } VLOG(3) << "GetKeyValueRequest: " << request->DebugString(); [call_opts, request, response, done = std::move(done), &cm = cancellation_manager_, token](const absl::Status& s) { // RPC call has completed (no longer needs to be cancelled if agent is // destroyed). cm.TryDeregisterCallback(token); // Retrieve server response. if (!s.ok()) { done(s); VLOG(3) << "GetKeyValueResponse: " << s; } else { done(response->kv().value()); VLOG(3) << "GetKeyValueResponse: " << response->DebugString(); } }); VLOG(3) << "GetKeyValueResponse: " << s; VLOG(3) << "GetKeyValueResponse: " << response->DebugString(); absl::StatusOr<std::string> CoordinationServiceAgentImpl::TryGetKeyValue( std::string_view key) { absl::Notification n; absl::StatusOr<std::string> result; TryGetKeyValueRequest request; request.set_key(key.data(), key.size()); VLOG(3) << "TryGetKeyValueRequest: " << request.DebugString(); TryGetKeyValueResponse response; leader_client_->TryGetKeyValueAsync( &request, &response, [&](const absl::Status& s) { if (s.ok()) { result = response.kv().value(); VLOG(3) << "TryGetKeyValueResponse: " << result.value(); } else { result = s; VLOG(3) << "TryGetKeyValueResponse: " << s; } n.Notify(); }); n.WaitForNotification(); return result; } VLOG(3) << "TryGetKeyValueRequest: " << request.DebugString(); &request, &response, [&](const absl::Status& s) { if (s.ok()) { result = response.kv().value(); VLOG(3) << "TryGetKeyValueResponse: " << result.value(); } else { result = s; VLOG(3) << "TryGetKeyValueResponse: " << s; } n.Notify(); }); VLOG(3) << "TryGetKeyValueResponse: " << result.value(); VLOG(3) << "TryGetKeyValueResponse: " << s; CoordinationServiceAgentImpl::GetKeyValueDir(std::string_view key) { absl::Notification n; absl::StatusOr<std::vector<KeyValueEntry>> result; GetKeyValueDirAsync( key, [&n, &result]( absl::StatusOr<std::vector<KeyValueEntry>> status_or_value) { result = std::move(status_or_value); n.Notify(); }); n.WaitForNotification(); return result; } key, [&n, &result]( absl::StatusOr<std::vector<KeyValueEntry>> status_or_value) { result = std::move(status_or_value); n.Notify(); }); void CoordinationServiceAgentImpl::GetKeyValueDirAsync( std::string_view key, StatusOrValueDirCallback done) { auto request = std::make_shared<GetKeyValueDirRequest>(); request->set_directory_key(key.data(), key.size()); VLOG(3) << "GetKeyValueDirRequest: " << request->DebugString(); auto response = std::make_shared<GetKeyValueDirResponse>(); leader_client_->GetKeyValueDirAsync( request.get(), response.get(), [request, response, done = std::move(done)](const absl::Status& s) { if (!s.ok()) { done(s); VLOG(3) << "GetKeyValueDirResponse: " << s; } else { VLOG(3) << "GetKeyValueDirResponse: " << response->DebugString(); std::vector<KeyValueEntry> kv_in_directory = { std::make_move_iterator(response->kv().begin()), std::make_move_iterator(response->kv().end())}; done(kv_in_directory); } }); } VLOG(3) << "GetKeyValueDirRequest: " << request->DebugString(); [request, response, done = std::move(done)](const absl::Status& s) { if (!s.ok()) { done(s); VLOG(3) << "GetKeyValueDirResponse: " << s; } else { VLOG(3) << "GetKeyValueDirResponse: " << response->DebugString(); std::vector<KeyValueEntry> kv_in_directory = { std::make_move_iterator(response->kv().begin()), std::make_move_iterator(response->kv().end())}; done(kv_in_directory); } }); VLOG(3) << "GetKeyValueDirResponse: " << s; VLOG(3) << "GetKeyValueDirResponse: " << response->DebugString(); absl::Status CoordinationServiceAgentImpl::InsertKeyValue( std::string_view key, std::string_view value) { return InsertKeyValue(key, value, /*allow_overwrite=*/false); } absl::Status CoordinationServiceAgentImpl::InsertKeyValue( std::string_view key, std::string_view value, bool allow_overwrite) { InsertKeyValueRequest request; request.mutable_kv()->set_key(key.data(), key.size()); request.mutable_kv()->set_value(value.data(), value.size()); request.set_allow_overwrite(allow_overwrite); VLOG(3) << "InsertKeyValueRequest: " << request.DebugString(); InsertKeyValueResponse response; absl::Status status; absl::Notification n; leader_client_->InsertKeyValueAsync(&request, &response, [&](absl::Status s) { status = s; n.Notify(); }); n.WaitForNotification(); VLOG(3) << "InsertKeyValueResponse: " << status; return status; } VLOG(3) << "InsertKeyValueRequest: " << request.DebugString(); leader_client_->InsertKeyValueAsync(&request, &response, [&](absl::Status s) { status = s; n.Notify(); }); VLOG(3) << "InsertKeyValueResponse: " << status; absl::Status CoordinationServiceAgentImpl::DeleteKeyValue( std::string_view key) { DeleteKeyValueRequest request; request.set_key(key.data(), key.size()); request.set_is_directory(true); VLOG(3) << "DeleteKeyValueRequest: " << request.DebugString(); DeleteKeyValueResponse response; absl::Status status; absl::Notification n; leader_client_->DeleteKeyValueAsync(&request, &response, [&](absl::Status s) { status = s; n.Notify(); }); n.WaitForNotification(); VLOG(3) << "DeleteKeyValueResponse " << status; return absl::OkStatus(); } VLOG(3) << "DeleteKeyValueRequest: " << request.DebugString(); leader_client_->DeleteKeyValueAsync(&request, &response, [&](absl::Status s) { status = s; n.Notify(); }); VLOG(3) << "DeleteKeyValueResponse " << status; absl::Status CoordinationServiceAgentImpl::UpdateKeyValue( std::string_view key, std::string_view value) { return MakeCoordinationError(absl::UnimplementedError( "CoordinationServiceAgent::UpdateKeyValue is not implemented.")); } absl::Status CoordinationServiceAgentImpl::StartWatchKey( std::string_view key, CoordinationServiceAgentImpl::ChangedKeyValuesCallback on_change) { return MakeCoordinationError(absl::UnimplementedError( "CoordinationServiceAgent::StartWatchKey is not implemented.")); } absl::Status CoordinationServiceAgentImpl::StopWatchKey(std::string_view key) { return MakeCoordinationError(absl::UnimplementedError( "CoordinationServiceAgent::StopWatchKey is not implemented.")); } void CoordinationServiceAgentImpl::SetError(const absl::Status& error) { assert(!error.ok()); absl::MutexLock l(&state_mu_); if (state_ == CoordinatedTaskState::TASKSTATE_ERROR) return; LOG(ERROR) << "Coordination agent is set to ERROR: " << error; state_ = CoordinatedTaskState::TASKSTATE_ERROR; status_ = error; error_fn_(error); } absl::Status CoordinationServiceAgentImpl::ActivateWatch( std::string_view key, const std::map<std::string, std::string>& kvs) { return MakeCoordinationError(absl::UnimplementedError( "CoordinationServiceAgent::ActivateWatch is not implemented.")); } absl::Status CoordinationServiceAgentImpl::WaitAtBarrier( std::string_view barrier_id, absl::Duration timeout, const std::vector<CoordinatedTask>& tasks) { absl::Status status; absl::Notification n; WaitAtBarrierAsync(barrier_id, timeout, tasks, [&](absl::Status s) { status = s; n.Notify(); }); n.WaitForNotification(); return status; } WaitAtBarrierAsync(barrier_id, timeout, tasks, [&](absl::Status s) { status = s; n.Notify(); }); void CoordinationServiceAgentImpl::WaitAtBarrierAsync( std::string_view barrier_id, absl::Duration timeout, const std::vector<CoordinatedTask>& tasks, StatusCallback done) { absl::Status agent_running_status = ValidateRunningAgent(/*allow_disconnected=*/true); if (!agent_running_status.ok()) { done(agent_running_status); return; } { absl::MutexLock l(&state_mu_); auto [it, inserted] = used_barrier_ids_.insert(std::string(barrier_id)); if (!inserted) { done(absl::FailedPreconditionError(absl::StrCat( "WaitAtBarrier() should not be called with the same id more than " "once. Barrier id: ", barrier_id))); return; } } auto request = std::make_shared<BarrierRequest>(); auto response = std::make_shared<BarrierResponse>(); request->set_barrier_id(std::string(barrier_id)); request->set_barrier_timeout_in_ms(timeout / absl::Milliseconds(1)); *request->mutable_source_task() = task_; *request->mutable_tasks() = {tasks.begin(), tasks.end()}; VLOG(3) << "WaitAtBarrierRequest: " << request->DebugString(); leader_client_->BarrierAsync( request.get(), response.get(), [request, response, done = std::move(done)](const absl::Status& s) { done(s); VLOG(3) << "WaitAtBarrierResponse: " << s; }); } VLOG(3) << "WaitAtBarrierRequest: " << request->DebugString(); [request, response, done = std::move(done)](const absl::Status& s) { done(s); VLOG(3) << "WaitAtBarrierResponse: " << s; }); VLOG(3) << "WaitAtBarrierResponse: " << s; absl::Status CoordinationServiceAgentImpl::CancelBarrier( std::string_view barrier_id) { absl::Status status; absl::Notification n; CancelBarrierAsync(barrier_id, [&](const absl::Status& s) { status = s; n.Notify(); }); n.WaitForNotification(); return status; } CancelBarrierAsync(barrier_id, [&](const absl::Status& s) { status = s; n.Notify(); }); void CoordinationServiceAgentImpl::CancelBarrierAsync( std::string_view barrier_id, StatusCallback done) { absl::Status agent_running_status = ValidateRunningAgent(/*allow_disconnected=*/true); if (!agent_running_status.ok()) { done(agent_running_status); return; } auto request = std::make_shared<CancelBarrierRequest>(); auto response = std::make_shared<CancelBarrierResponse>(); request->set_barrier_id(std::string(barrier_id)); *request->mutable_source_task() = task_; VLOG(3) << "CancelBarrierRequest: " << request->DebugString(); leader_client_->CancelBarrierAsync( request.get(), response.get(), [request, response, done = std::move(done)](const absl::Status& s) { done(s); VLOG(3) << "CancelBarrierResponse: " << s; }); } VLOG(3) << "CancelBarrierRequest: " << request->DebugString(); [request, response, done = std::move(done)](const absl::Status& s) { done(s); VLOG(3) << "CancelBarrierResponse: " << s; }); VLOG(3) << "CancelBarrierResponse: " << s; absl::Status CoordinationServiceAgentImpl::ValidateRunningAgent( bool allow_disconnected) { absl::MutexLock l(&state_mu_); switch (state_) { case CoordinatedTaskState::TASKSTATE_CONNECTED: return absl::OkStatus(); case CoordinatedTaskState::TASKSTATE_UNINITIALIZED: return MakeCoordinationError(absl::FailedPreconditionError( "Agent must be in CONNECTED state. It is currently UNINITIALIZED.")); case CoordinatedTaskState::TASKSTATE_DISCONNECTED: if (allow_disconnected) return absl::OkStatus(); return MakeCoordinationError(absl::FailedPreconditionError( "Agent must be in CONNECTED state. It is currently DISCONNECTED.")); case CoordinatedTaskState::TASKSTATE_ERROR: return MakeCoordinationError(absl::FailedPreconditionError( "Agent must be in CONNECTED state. It is currently in ERROR.")); default: return MakeCoordinationError(absl::FailedPreconditionError(absl::StrCat( "Agent is not in CONNECTED state. Current state: ", state_))); } } absl::StatusOr<Env*> CoordinationServiceAgentImpl::GetEnv() { if (!IsInitialized()) { return MakeCoordinationError(absl::FailedPreconditionError( "Coordination service agent has not been initialized.")); } if (env_ == nullptr) { return MakeCoordinationError( absl::FailedPreconditionError("Coordination service agent was not " "initialized with a valid Env* object.")); } return env_; } std::unique_ptr<CoordinationServiceAgent> CreateCoordinationServiceAgent() { return std::make_unique<CoordinationServiceAgentImpl>(); }
#include "xla/tsl/distributed_runtime/coordination/coordination_service_agent.h" #include <memory> #include <ostream> #include <string> #include <utility> #include <vector> #include "absl/log/check.h" #include "absl/log/log.h" #include "absl/memory/memory.h" #include "absl/status/status.h" #include "absl/time/clock.h" #include "absl/time/time.h" #include "xla/tsl/distributed_runtime/call_options.h" #include "xla/tsl/distributed_runtime/coordination/coordination_client.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/env.h" #include "tsl/platform/status.h" #include "tsl/platform/test.h" #include "tsl/protobuf/coordination_config.pb.h" #include "tsl/protobuf/coordination_service.pb.h" class CoordinationServiceAgentTest : public ::testing::Test { public: void SetUp() override { ON_CALL(*client_, RegisterTaskAsync(_, _, _, _)) .WillByDefault(InvokeArgument<3>(absl::OkStatus())); ON_CALL(*client_, HeartbeatAsync(_, _, _, _)) .WillByDefault(InvokeArgument<3>(absl::OkStatus())); ON_CALL(*client_, ShutdownTaskAsync(_, _, _, _)) .WillByDefault(InvokeArgument<3>(absl::OkStatus())); ON_CALL(*client_, ReportErrorToServiceAsync(_, _, _)) .WillByDefault(InvokeArgument<2>(absl::OkStatus())); ON_CALL(*client_, ResetTaskAsync(_, _, _)) .WillByDefault(InvokeArgument<2>(absl::OkStatus())); ON_CALL(*client_, BarrierAsync(_, _, _)) .WillByDefault(InvokeArgument<2>(absl::OkStatus())); ON_CALL(*client_, GetTaskStateAsync(_, _, _)) .WillByDefault(InvokeArgument<2>(absl::OkStatus())); } // Should be called after mocking service responses, before testing the agent. void InitializeAgent(CoordinationServiceConfig config = {}) { config.set_service_leader("test_leader"); TF_ASSERT_OK(agent_->Initialize( Env::Default(), /*job_name=*/"test_job", /*task_id=*/0, config, std::move(client_), /*error_fn=*/[](absl::Status s) { LOG(ERROR) << "Coordination agent is set to error: " << s; })); } TestCoordinationClient* GetClient() { // InitializeAgent() transfers ownership of the coordination client. CHECK(client_ != nullptr) << "GetClient() was called after InitializeAgent()"; return client_.get(); } protected: std::unique_ptr<CoordinationServiceAgent> agent_ = CreateCoordinationServiceAgent(); std::unique_ptr<TestCoordinationClient> client_ = std::make_unique<TestCoordinationClient>(); }; TEST_F(CoordinationServiceAgentTest, ConnectAfterResetError) { // Connect coordination agent and set it to error. InitializeAgent(); TF_ASSERT_OK(agent_->Connect()); TF_ASSERT_OK(agent_->ReportError(absl::InternalError("Test Error."))); // Reset error. TF_ASSERT_OK(agent_->Reset()); // Agent should be able to reconnect to the service after resetting. TF_EXPECT_OK(agent_->Connect()); }
CoordinationServiceAgentTest_GetOwnTask
xla/tsl/distributed_runtime/coordination/coordination_service_agent_test.cc
CoordinationServiceAgentImpl() = default; ~CoordinationServiceAgentImpl() override { absl::Status s = ShutdownInternal(); VLOG(3) << "Coordination agent dtor failed with status: " << s; } VLOG(3) << "Coordination agent dtor failed with status: " << s; absl::Status CoordinationServiceAgentImpl::Initialize( Env* env, std::string_view job_name, int task_id, const CoordinationServiceConfig& configs, std::unique_ptr<CoordinationClient> leader_client, StatusCallback error_fn) { CoordinatedTask task; task.set_job_name(std::string(job_name)); task.set_task_id(task_id); return Initialize(env, task, configs, std::move(leader_client), error_fn); } absl::Status CoordinationServiceAgentImpl::Initialize( Env* env, const CoordinatedTask& task, const CoordinationServiceConfig& configs, std::unique_ptr<CoordinationClient> leader_client, StatusCallback error_fn) { enabled_usage_metric->GetCell()->Set(true); absl::MutexLock l(&state_mu_); if (state_ != CoordinatedTaskState::TASKSTATE_UNINITIALIZED) { return MakeCoordinationError(absl::FailedPreconditionError( "Coordination service agent has already been initialized.")); } env_ = env; task_ = task; configs_ = configs; if (configs_.service_leader().empty()) { return MakeCoordinationError(absl::InvalidArgumentError( "CoordinationServiceAgent must be initialized with a valid leader.")); } leader_client_ = std::move(leader_client); if (leader_client_ == nullptr) { return MakeCoordinationError(absl::InvalidArgumentError( "CoordinationServiceAgent must have a valid leader client.")); } error_fn_ = error_fn; state_ = CoordinatedTaskState::TASKSTATE_DISCONNECTED; return absl::OkStatus(); } bool CoordinationServiceAgentImpl::IsInitialized() { absl::MutexLock l(&state_mu_); return state_ != CoordinatedTaskState::TASKSTATE_UNINITIALIZED; } bool CoordinationServiceAgentImpl::IsConnected() { absl::MutexLock l(&state_mu_); return state_ == CoordinatedTaskState::TASKSTATE_CONNECTED; } bool CoordinationServiceAgentImpl::IsError() { absl::MutexLock l(&state_mu_); return state_ == CoordinatedTaskState::TASKSTATE_ERROR; } void CoordinationServiceAgentImpl::StopHeartbeat() { { absl::MutexLock l(&heartbeat_thread_shutdown_mu_); shutting_down_ = true; heartbeat_thread_cv_.SignalAll(); } heartbeat_thread_ = nullptr; } absl::Status CoordinationServiceAgentImpl::Connect() { VLOG(3) << "Agent has started trying to Connect()."; { absl::MutexLock l(&state_mu_); if (state_ != CoordinatedTaskState::TASKSTATE_DISCONNECTED) { return MakeCoordinationError(absl::FailedPreconditionError( "Coordination service agent is not in DISCONNECTED state.")); } } absl::Status connect_status = absl::UnknownError("Connection not attempted yet."); RegisterTaskRequest request; *request.mutable_source_task() = task_; request.set_incarnation(incarnation_id_); RegisterTaskResponse response; const int64_t register_timeout = configs_.cluster_register_timeout_in_ms() > 0 ? configs_.cluster_register_timeout_in_ms() : absl::ToInt64Milliseconds(kDefaultClusterRegisterTimeout); const absl::Time deadline = absl::Now() + absl::Milliseconds(register_timeout); int attempt = 0; std::default_random_engine generator; std::uniform_real_distribution<double> distribution(0.0, 1.0); do { ++attempt; CallOptions call_opts; call_opts.SetTimeout(absl::ToInt64Milliseconds(deadline - absl::Now())); absl::Notification n; leader_client_->RegisterTaskAsync( &call_opts, &request, &response, [&](absl::Status s) { if (s.ok()) { leader_incarnation_ = response.leader_incarnation(); { absl::MutexLock l(&state_mu_); state_ = CoordinatedTaskState::TASKSTATE_CONNECTED; } } connect_status = s; n.Notify(); }); n.WaitForNotification(); if (!connect_status.ok()) { // Exponential backoff with jitter. Note we will retry for `init_timeout` // time in total; the `14` here corresponds to an ~16s maximum interval // between connection attempts. const int backoff = 1 << std::min(14, attempt); absl::SleepFor(absl::Milliseconds(backoff * distribution(generator))); } } while (!connect_status.ok() && absl::Now() < deadline && // Retries are attempted for: // 1. RPC errors. // 2. aborted duplicate task registration error - this means that // this task restarted and is trying to reconnect but the service // has not restarted yet. // 3. service has not been enabled - this could happen in the single // client scenario, where the server has been started but the service // cannot be used yet (nullptr). Presumably the service is in the // process of being enabled. (connect_status.GetPayload(CoordinationErrorPayloadKey()) == std::nullopt || absl::IsAborted(connect_status) || absl::IsInternal(connect_status))); if (!connect_status.ok()) { SetError(connect_status); return connect_status; } LOG(INFO) << "Coordination agent has successfully connected."; heartbeat_thread_.reset( env_->StartThread(ThreadOptions(), kHeartbeatThread, [this]() -> void { HeartbeatRequest request; *request.mutable_source_task() = task_; request.set_incarnation(incarnation_id_); HeartbeatResponse response; const int64_t heartbeat_interval_ms = configs_.heartbeat_timeout_in_ms() > 0 ? configs_.heartbeat_timeout_in_ms() / 2 : absl::ToInt64Milliseconds(kDefaultHeartbeatTimeout) / 2; CallOptions call_opts; call_opts.SetTimeout(heartbeat_interval_ms); while (true) { absl::Status status; absl::Notification n; // Heartbeat RPC implementation automatically retries to tolerate // transient network failures. VLOG(10) << "HeartbeatRequest: " << request.DebugString(); leader_client_->HeartbeatAsync(&call_opts, &request, &response, [&](absl::Status s) { status = s; n.Notify(); }); n.WaitForNotification(); VLOG(10) << "HeartbeatResponse: " << status; if (!status.ok()) { // Ignore heartbeat errors and exit thread if shutting down. For // example, the agent may send a heartbeat right after Shutdown() // started, but before StopHeartbeat() and end of Shutdown(). This // results in an unexpected heartbeat error. // Waiting for a second allows us to identify if errors are due to // inflight heartbeats sent during shutdown and can be ignored. absl::SleepFor(absl::Seconds(1)); { absl::MutexLock l(&heartbeat_thread_shutdown_mu_); if (shutting_down_) { return; } } SetError(status); } else if (response.leader_incarnation() != leader_incarnation_) { SetError(MakeCoordinationError( absl::AbortedError("Leader incarnation ID mismatch: the " "coordination leader has restarted."))); } // Send next heartbeat after an interval. { absl::MutexLock l(&heartbeat_thread_shutdown_mu_); heartbeat_thread_cv_.WaitWithTimeout( &heartbeat_thread_shutdown_mu_, absl::Milliseconds(heartbeat_interval_ms)); if (shutting_down_) { return; } } } })); return absl::OkStatus(); } VLOG(3) << "Agent has started trying to Connect()."; &call_opts, &request, &response, [&](absl::Status s) { if (s.ok()) { leader_incarnation_ = response.leader_incarnation(); { absl::MutexLock l(&state_mu_); state_ = CoordinatedTaskState::TASKSTATE_CONNECTED; } } connect_status = s; n.Notify(); }); env_->StartThread(ThreadOptions(), kHeartbeatThread, [this]() -> void { HeartbeatRequest request; *request.mutable_source_task() = task_; request.set_incarnation(incarnation_id_); HeartbeatResponse response; const int64_t heartbeat_interval_ms = configs_.heartbeat_timeout_in_ms() > 0 ? configs_.heartbeat_timeout_in_ms() / 2 : absl::ToInt64Milliseconds(kDefaultHeartbeatTimeout) / 2; CallOptions call_opts; call_opts.SetTimeout(heartbeat_interval_ms); while (true) { absl::Status status; absl::Notification n; // Heartbeat RPC implementation automatically retries to tolerate // transient network failures. VLOG(10) << "HeartbeatRequest: " << request.DebugString(); leader_client_->HeartbeatAsync(&call_opts, &request, &response, [&](absl::Status s) { status = s; n.Notify(); }); n.WaitForNotification(); VLOG(10) << "HeartbeatResponse: " << status; if (!status.ok()) { // Ignore heartbeat errors and exit thread if shutting down. For // example, the agent may send a heartbeat right after Shutdown() // started, but before StopHeartbeat() and end of Shutdown(). This // results in an unexpected heartbeat error. // Waiting for a second allows us to identify if errors are due to // inflight heartbeats sent during shutdown and can be ignored. absl::SleepFor(absl::Seconds(1)); { absl::MutexLock l(&heartbeat_thread_shutdown_mu_); if (shutting_down_) { return; } } SetError(status); } else if (response.leader_incarnation() != leader_incarnation_) { SetError(MakeCoordinationError( absl::AbortedError("Leader incarnation ID mismatch: the " "coordination leader has restarted."))); } // Send next heartbeat after an interval. { absl::MutexLock l(&heartbeat_thread_shutdown_mu_); heartbeat_thread_cv_.WaitWithTimeout( &heartbeat_thread_shutdown_mu_, absl::Milliseconds(heartbeat_interval_ms)); if (shutting_down_) { return; } } } })); VLOG(10) << "HeartbeatRequest: " << request.DebugString(); [&](absl::Status s) { status = s; n.Notify(); }); VLOG(10) << "HeartbeatResponse: " << status; absl::Status CoordinationServiceAgentImpl::WaitForAllTasks( const DeviceInfo& local_devices) { absl::Status agent_running_status = ValidateRunningAgent(); if (!agent_running_status.ok()) { return agent_running_status; } WaitForAllTasksRequest request; *request.mutable_source_task() = task_; *request.mutable_device_info() = local_devices; VLOG(3) << "WaitForAllTasksRequest: " << request.DebugString(); WaitForAllTasksResponse response; absl::Status status; absl::Notification n; leader_client_->WaitForAllTasksAsync(&request, &response, [&](absl::Status s) { status = s; n.Notify(); }); n.WaitForNotification(); if (!status.ok()) { VLOG(3) << "WaitForAllTasksResponse: " << status; SetError(status); return status; } VLOG(3) << "WaitForAllTasksResponse: " << response.DebugString(); cluster_devices_ = response.device_info(); return absl::OkStatus(); } VLOG(3) << "WaitForAllTasksRequest: " << request.DebugString(); [&](absl::Status s) { status = s; n.Notify(); }); VLOG(3) << "WaitForAllTasksResponse: " << status; VLOG(3) << "WaitForAllTasksResponse: " << response.DebugString(); const DeviceInfo& CoordinationServiceAgentImpl::GetClusterDeviceInfo() { return cluster_devices_; } absl::StatusOr<CoordinatedTask> CoordinationServiceAgentImpl::GetOwnTask() { if (!IsInitialized()) { return MakeCoordinationError(absl::FailedPreconditionError( "Agent has not been initialized; we do not " "know the associated task yet.")); } return task_; } CoordinationServiceAgentImpl::GetTaskState( const std::vector<CoordinatedTask>& tasks) { GetTaskStateRequest request; *request.mutable_source_task() = {tasks.begin(), tasks.end()}; GetTaskStateResponse response; absl::Notification n; absl::StatusOr<std::vector<CoordinatedTaskStateInfo>> result; leader_client_->GetTaskStateAsync( &request, &response, [&](const absl::Status& s) { if (s.ok()) { result = std::vector<CoordinatedTaskStateInfo>( std::make_move_iterator(response.task_state().begin()), std::make_move_iterator(response.task_state().end())); } else { result = s; } n.Notify(); }); n.WaitForNotification(); return result; } &request, &response, [&](const absl::Status& s) { if (s.ok()) { result = std::vector<CoordinatedTaskStateInfo>( std::make_move_iterator(response.task_state().begin()), std::make_move_iterator(response.task_state().end())); } else { result = s; } n.Notify(); }); absl::Status CoordinationServiceAgentImpl::ReportError( const absl::Status& error) { { absl::MutexLock l(&state_mu_); if (state_ == CoordinatedTaskState::TASKSTATE_UNINITIALIZED) { return MakeCoordinationError(absl::FailedPreconditionError( "Coordination service agent must be initialized first before " "reporting error.")); } else if (state_ == CoordinatedTaskState::TASKSTATE_ERROR) { return MakeCoordinationError(absl::FailedPreconditionError( "Coordination service agent is already in error state.")); } } SetError(MakeCoordinationError(error, task_, /*is_reported_error=*/true)); LOG(INFO) << "Reporting error to coordination service: " << error; ReportErrorToServiceRequest request; request.set_error_code(error.raw_code()); request.set_error_message(std::string(error.message())); *request.mutable_error_origin() = task_; VLOG(5) << "ReportErrorToServiceRequest: " << request.DebugString(); ReportErrorToServiceResponse response; absl::Notification n; leader_client_->ReportErrorToServiceAsync( &request, &response, [&](absl::Status s) { VLOG(5) << "ReportErrorToServiceResponse: " << s; if (!s.ok()) { LOG(ERROR) << "Encountered another error when reporting error to " "coordination service: " << s << "\nThis is usually caused by an earlier error during " "execution. Check the logs (this task or the leader) for " "an earlier error to debug further."; } n.Notify(); }); n.WaitForNotification(); return absl::OkStatus(); } VLOG(5) << "ReportErrorToServiceRequest: " << request.DebugString(); &request, &response, [&](absl::Status s) { VLOG(5) << "ReportErrorToServiceResponse: " << s; if (!s.ok()) { LOG(ERROR) << "Encountered another error when reporting error to " "coordination service: " << s << "\nThis is usually caused by an earlier error during " "execution. Check the logs (this task or the leader) for " "an earlier error to debug further."; } n.Notify(); }); VLOG(5) << "ReportErrorToServiceResponse: " << s; absl::Status CoordinationServiceAgentImpl::Shutdown() { return ShutdownInternal(); } absl::Status CoordinationServiceAgentImpl::ShutdownInternal() { absl::Status status = absl::OkStatus(); bool is_connected = false; { absl::MutexLock l(&state_mu_); is_connected = state_ == CoordinatedTaskState::TASKSTATE_CONNECTED; } // Disconnect agent from service. if (!configs_.agent_destruction_without_shutdown() && is_connected) { LOG(INFO) << "Coordination agent has initiated Shutdown()."; ShutdownTaskRequest request; *request.mutable_source_task() = task_; ShutdownTaskResponse response; CallOptions call_opts; const int64_t shutdown_timeout = configs_.shutdown_barrier_timeout_in_ms() > 0 ? configs_.shutdown_barrier_timeout_in_ms() : absl::ToInt64Milliseconds(kDefaultShutdownTimeout); call_opts.SetTimeout(shutdown_timeout); absl::Notification n; leader_client_->ShutdownTaskAsync(&call_opts, &request, &response, [&status, &n](absl::Status s) { status = s; n.Notify(); }); n.WaitForNotification(); if (status.ok()) { LOG(INFO) << "Coordination agent has successfully shut down."; } else { LOG(ERROR) << "Failed to disconnect from coordination service with status: " << status << "\nProceeding with agent shutdown anyway. This is usually caused " "by an earlier error during execution. Check the logs (this task " "or the leader) for an earlier error to debug further."; } } // Tear down agent. StopHeartbeat(); { absl::MutexLock l(&state_mu_); if (state_ == CoordinatedTaskState::TASKSTATE_ERROR) { const std::string status_message = absl::StrCat( "Shutdown() was called while coordination agent is in error state, " "implying that distributed execution failed. Note: agent will still " "shutdown anyway. Agent status: ", status_.ToString(), "\nThis is usually caused by an earlier error during execution. " "Check the logs (this task or the leader) for an earlier error to " "debug further."); status = MakeCoordinationError(absl::FailedPreconditionError(status_message)); LOG(ERROR) << status_message; } state_ = CoordinatedTaskState::TASKSTATE_DISCONNECTED; } // Cancel all pending GetKeyValue() RPC calls. cancellation_manager_.StartCancel(); return status; } [&status, &n](absl::Status s) { status = s; n.Notify(); }); absl::Status CoordinationServiceAgentImpl::Reset() { { absl::MutexLock l(&state_mu_); if (state_ != CoordinatedTaskState::TASKSTATE_ERROR) { return MakeCoordinationError(absl::FailedPreconditionError( "Reset() failed: coordination service agent is not in ERROR state.")); } } ResetTaskRequest request; *request.mutable_source_task() = task_; VLOG(3) << "ResetTaskRequest: " << request.DebugString(); ResetTaskResponse response; absl::Status status; absl::Notification n; leader_client_->ResetTaskAsync(&request, &response, [&status, &n](absl::Status s) { status = s; n.Notify(); }); n.WaitForNotification(); VLOG(3) << "ResetTaskResponse: " << status; if (!status.ok()) { return status; } // Reset agent state. StopHeartbeat(); { absl::MutexLock l(&state_mu_); state_ = CoordinatedTaskState::TASKSTATE_DISCONNECTED; } { absl::MutexLock l(&heartbeat_thread_shutdown_mu_); shutting_down_ = false; } LOG(INFO) << "Coordination agent has been reset."; return status; } VLOG(3) << "ResetTaskRequest: " << request.DebugString(); [&status, &n](absl::Status s) { status = s; n.Notify(); }); VLOG(3) << "ResetTaskResponse: " << status; absl::StatusOr<std::string> CoordinationServiceAgentImpl::GetKeyValue( std::string_view key) { return GetKeyValue(key, /*timeout=*/absl::InfiniteDuration()); } absl::StatusOr<std::string> CoordinationServiceAgentImpl::GetKeyValue( std::string_view key, absl::Duration timeout) { auto n = std::make_shared<absl::Notification>(); auto result = std::make_shared<absl::StatusOr<std::string>>(); GetKeyValueAsync( key, [n, result](const absl::StatusOr<std::string>& status_or_value) { *result = status_or_value; n->Notify(); }); bool call_completed_before_timeout = n->WaitForNotificationWithTimeout(timeout); if (!call_completed_before_timeout) { VLOG(3) << "GetKeyValue(" << key << ") timed out after " << timeout; return MakeCoordinationError(absl::DeadlineExceededError(absl::Substitute( "GetKeyValue() timed out with key: $0 and duration: $1", key, absl::FormatDuration(timeout)))); } return *result; } key, [n, result](const absl::StatusOr<std::string>& status_or_value) { *result = status_or_value; n->Notify(); }); VLOG(3) << "GetKeyValue(" << key << ") timed out after " << timeout; std::shared_ptr<CallOptions> CoordinationServiceAgentImpl::GetKeyValueAsync( std::string_view key, StatusOrValueCallback done) { auto request = std::make_shared<GetKeyValueRequest>(); request->set_key(key.data(), key.size()); VLOG(3) << "GetKeyValueRequest: " << request->DebugString(); auto response = std::make_shared<GetKeyValueResponse>(); auto call_opts = std::make_shared<CallOptions>(); const CancellationToken token = cancellation_manager_.get_cancellation_token(); const bool already_cancelled = !cancellation_manager_.RegisterCallback( token, [call_opts]() { call_opts->StartCancel(); }); if (already_cancelled) { done(absl::CancelledError("GetKeyValueAsync() was cancelled.")); return call_opts; } leader_client_->GetKeyValueAsync( call_opts.get(), request.get(), response.get(), [call_opts, request, response, done = std::move(done), &cm = cancellation_manager_, token](const absl::Status& s) { // RPC call has completed (no longer needs to be cancelled if agent is // destroyed). cm.TryDeregisterCallback(token); // Retrieve server response. if (!s.ok()) { done(s); VLOG(3) << "GetKeyValueResponse: " << s; } else { done(response->kv().value()); VLOG(3) << "GetKeyValueResponse: " << response->DebugString(); } }); return call_opts; } VLOG(3) << "GetKeyValueRequest: " << request->DebugString(); [call_opts, request, response, done = std::move(done), &cm = cancellation_manager_, token](const absl::Status& s) { // RPC call has completed (no longer needs to be cancelled if agent is // destroyed). cm.TryDeregisterCallback(token); // Retrieve server response. if (!s.ok()) { done(s); VLOG(3) << "GetKeyValueResponse: " << s; } else { done(response->kv().value()); VLOG(3) << "GetKeyValueResponse: " << response->DebugString(); } }); VLOG(3) << "GetKeyValueResponse: " << s; VLOG(3) << "GetKeyValueResponse: " << response->DebugString(); absl::StatusOr<std::string> CoordinationServiceAgentImpl::TryGetKeyValue( std::string_view key) { absl::Notification n; absl::StatusOr<std::string> result; TryGetKeyValueRequest request; request.set_key(key.data(), key.size()); VLOG(3) << "TryGetKeyValueRequest: " << request.DebugString(); TryGetKeyValueResponse response; leader_client_->TryGetKeyValueAsync( &request, &response, [&](const absl::Status& s) { if (s.ok()) { result = response.kv().value(); VLOG(3) << "TryGetKeyValueResponse: " << result.value(); } else { result = s; VLOG(3) << "TryGetKeyValueResponse: " << s; } n.Notify(); }); n.WaitForNotification(); return result; } VLOG(3) << "TryGetKeyValueRequest: " << request.DebugString(); &request, &response, [&](const absl::Status& s) { if (s.ok()) { result = response.kv().value(); VLOG(3) << "TryGetKeyValueResponse: " << result.value(); } else { result = s; VLOG(3) << "TryGetKeyValueResponse: " << s; } n.Notify(); }); VLOG(3) << "TryGetKeyValueResponse: " << result.value(); VLOG(3) << "TryGetKeyValueResponse: " << s; CoordinationServiceAgentImpl::GetKeyValueDir(std::string_view key) { absl::Notification n; absl::StatusOr<std::vector<KeyValueEntry>> result; GetKeyValueDirAsync( key, [&n, &result]( absl::StatusOr<std::vector<KeyValueEntry>> status_or_value) { result = std::move(status_or_value); n.Notify(); }); n.WaitForNotification(); return result; } key, [&n, &result]( absl::StatusOr<std::vector<KeyValueEntry>> status_or_value) { result = std::move(status_or_value); n.Notify(); }); void CoordinationServiceAgentImpl::GetKeyValueDirAsync( std::string_view key, StatusOrValueDirCallback done) { auto request = std::make_shared<GetKeyValueDirRequest>(); request->set_directory_key(key.data(), key.size()); VLOG(3) << "GetKeyValueDirRequest: " << request->DebugString(); auto response = std::make_shared<GetKeyValueDirResponse>(); leader_client_->GetKeyValueDirAsync( request.get(), response.get(), [request, response, done = std::move(done)](const absl::Status& s) { if (!s.ok()) { done(s); VLOG(3) << "GetKeyValueDirResponse: " << s; } else { VLOG(3) << "GetKeyValueDirResponse: " << response->DebugString(); std::vector<KeyValueEntry> kv_in_directory = { std::make_move_iterator(response->kv().begin()), std::make_move_iterator(response->kv().end())}; done(kv_in_directory); } }); } VLOG(3) << "GetKeyValueDirRequest: " << request->DebugString(); [request, response, done = std::move(done)](const absl::Status& s) { if (!s.ok()) { done(s); VLOG(3) << "GetKeyValueDirResponse: " << s; } else { VLOG(3) << "GetKeyValueDirResponse: " << response->DebugString(); std::vector<KeyValueEntry> kv_in_directory = { std::make_move_iterator(response->kv().begin()), std::make_move_iterator(response->kv().end())}; done(kv_in_directory); } }); VLOG(3) << "GetKeyValueDirResponse: " << s; VLOG(3) << "GetKeyValueDirResponse: " << response->DebugString(); absl::Status CoordinationServiceAgentImpl::InsertKeyValue( std::string_view key, std::string_view value) { return InsertKeyValue(key, value, /*allow_overwrite=*/false); } absl::Status CoordinationServiceAgentImpl::InsertKeyValue( std::string_view key, std::string_view value, bool allow_overwrite) { InsertKeyValueRequest request; request.mutable_kv()->set_key(key.data(), key.size()); request.mutable_kv()->set_value(value.data(), value.size()); request.set_allow_overwrite(allow_overwrite); VLOG(3) << "InsertKeyValueRequest: " << request.DebugString(); InsertKeyValueResponse response; absl::Status status; absl::Notification n; leader_client_->InsertKeyValueAsync(&request, &response, [&](absl::Status s) { status = s; n.Notify(); }); n.WaitForNotification(); VLOG(3) << "InsertKeyValueResponse: " << status; return status; } VLOG(3) << "InsertKeyValueRequest: " << request.DebugString(); leader_client_->InsertKeyValueAsync(&request, &response, [&](absl::Status s) { status = s; n.Notify(); }); VLOG(3) << "InsertKeyValueResponse: " << status; absl::Status CoordinationServiceAgentImpl::DeleteKeyValue( std::string_view key) { DeleteKeyValueRequest request; request.set_key(key.data(), key.size()); request.set_is_directory(true); VLOG(3) << "DeleteKeyValueRequest: " << request.DebugString(); DeleteKeyValueResponse response; absl::Status status; absl::Notification n; leader_client_->DeleteKeyValueAsync(&request, &response, [&](absl::Status s) { status = s; n.Notify(); }); n.WaitForNotification(); VLOG(3) << "DeleteKeyValueResponse " << status; return absl::OkStatus(); } VLOG(3) << "DeleteKeyValueRequest: " << request.DebugString(); leader_client_->DeleteKeyValueAsync(&request, &response, [&](absl::Status s) { status = s; n.Notify(); }); VLOG(3) << "DeleteKeyValueResponse " << status; absl::Status CoordinationServiceAgentImpl::UpdateKeyValue( std::string_view key, std::string_view value) { return MakeCoordinationError(absl::UnimplementedError( "CoordinationServiceAgent::UpdateKeyValue is not implemented.")); } absl::Status CoordinationServiceAgentImpl::StartWatchKey( std::string_view key, CoordinationServiceAgentImpl::ChangedKeyValuesCallback on_change) { return MakeCoordinationError(absl::UnimplementedError( "CoordinationServiceAgent::StartWatchKey is not implemented.")); } absl::Status CoordinationServiceAgentImpl::StopWatchKey(std::string_view key) { return MakeCoordinationError(absl::UnimplementedError( "CoordinationServiceAgent::StopWatchKey is not implemented.")); } void CoordinationServiceAgentImpl::SetError(const absl::Status& error) { assert(!error.ok()); absl::MutexLock l(&state_mu_); if (state_ == CoordinatedTaskState::TASKSTATE_ERROR) return; LOG(ERROR) << "Coordination agent is set to ERROR: " << error; state_ = CoordinatedTaskState::TASKSTATE_ERROR; status_ = error; error_fn_(error); } absl::Status CoordinationServiceAgentImpl::ActivateWatch( std::string_view key, const std::map<std::string, std::string>& kvs) { return MakeCoordinationError(absl::UnimplementedError( "CoordinationServiceAgent::ActivateWatch is not implemented.")); } absl::Status CoordinationServiceAgentImpl::WaitAtBarrier( std::string_view barrier_id, absl::Duration timeout, const std::vector<CoordinatedTask>& tasks) { absl::Status status; absl::Notification n; WaitAtBarrierAsync(barrier_id, timeout, tasks, [&](absl::Status s) { status = s; n.Notify(); }); n.WaitForNotification(); return status; } WaitAtBarrierAsync(barrier_id, timeout, tasks, [&](absl::Status s) { status = s; n.Notify(); }); void CoordinationServiceAgentImpl::WaitAtBarrierAsync( std::string_view barrier_id, absl::Duration timeout, const std::vector<CoordinatedTask>& tasks, StatusCallback done) { absl::Status agent_running_status = ValidateRunningAgent(/*allow_disconnected=*/true); if (!agent_running_status.ok()) { done(agent_running_status); return; } { absl::MutexLock l(&state_mu_); auto [it, inserted] = used_barrier_ids_.insert(std::string(barrier_id)); if (!inserted) { done(absl::FailedPreconditionError(absl::StrCat( "WaitAtBarrier() should not be called with the same id more than " "once. Barrier id: ", barrier_id))); return; } } auto request = std::make_shared<BarrierRequest>(); auto response = std::make_shared<BarrierResponse>(); request->set_barrier_id(std::string(barrier_id)); request->set_barrier_timeout_in_ms(timeout / absl::Milliseconds(1)); *request->mutable_source_task() = task_; *request->mutable_tasks() = {tasks.begin(), tasks.end()}; VLOG(3) << "WaitAtBarrierRequest: " << request->DebugString(); leader_client_->BarrierAsync( request.get(), response.get(), [request, response, done = std::move(done)](const absl::Status& s) { done(s); VLOG(3) << "WaitAtBarrierResponse: " << s; }); } VLOG(3) << "WaitAtBarrierRequest: " << request->DebugString(); [request, response, done = std::move(done)](const absl::Status& s) { done(s); VLOG(3) << "WaitAtBarrierResponse: " << s; }); VLOG(3) << "WaitAtBarrierResponse: " << s; absl::Status CoordinationServiceAgentImpl::CancelBarrier( std::string_view barrier_id) { absl::Status status; absl::Notification n; CancelBarrierAsync(barrier_id, [&](const absl::Status& s) { status = s; n.Notify(); }); n.WaitForNotification(); return status; } CancelBarrierAsync(barrier_id, [&](const absl::Status& s) { status = s; n.Notify(); }); void CoordinationServiceAgentImpl::CancelBarrierAsync( std::string_view barrier_id, StatusCallback done) { absl::Status agent_running_status = ValidateRunningAgent(/*allow_disconnected=*/true); if (!agent_running_status.ok()) { done(agent_running_status); return; } auto request = std::make_shared<CancelBarrierRequest>(); auto response = std::make_shared<CancelBarrierResponse>(); request->set_barrier_id(std::string(barrier_id)); *request->mutable_source_task() = task_; VLOG(3) << "CancelBarrierRequest: " << request->DebugString(); leader_client_->CancelBarrierAsync( request.get(), response.get(), [request, response, done = std::move(done)](const absl::Status& s) { done(s); VLOG(3) << "CancelBarrierResponse: " << s; }); } VLOG(3) << "CancelBarrierRequest: " << request->DebugString(); [request, response, done = std::move(done)](const absl::Status& s) { done(s); VLOG(3) << "CancelBarrierResponse: " << s; }); VLOG(3) << "CancelBarrierResponse: " << s; absl::Status CoordinationServiceAgentImpl::ValidateRunningAgent( bool allow_disconnected) { absl::MutexLock l(&state_mu_); switch (state_) { case CoordinatedTaskState::TASKSTATE_CONNECTED: return absl::OkStatus(); case CoordinatedTaskState::TASKSTATE_UNINITIALIZED: return MakeCoordinationError(absl::FailedPreconditionError( "Agent must be in CONNECTED state. It is currently UNINITIALIZED.")); case CoordinatedTaskState::TASKSTATE_DISCONNECTED: if (allow_disconnected) return absl::OkStatus(); return MakeCoordinationError(absl::FailedPreconditionError( "Agent must be in CONNECTED state. It is currently DISCONNECTED.")); case CoordinatedTaskState::TASKSTATE_ERROR: return MakeCoordinationError(absl::FailedPreconditionError( "Agent must be in CONNECTED state. It is currently in ERROR.")); default: return MakeCoordinationError(absl::FailedPreconditionError(absl::StrCat( "Agent is not in CONNECTED state. Current state: ", state_))); } } absl::StatusOr<Env*> CoordinationServiceAgentImpl::GetEnv() { if (!IsInitialized()) { return MakeCoordinationError(absl::FailedPreconditionError( "Coordination service agent has not been initialized.")); } if (env_ == nullptr) { return MakeCoordinationError( absl::FailedPreconditionError("Coordination service agent was not " "initialized with a valid Env* object.")); } return env_; } std::unique_ptr<CoordinationServiceAgent> CreateCoordinationServiceAgent() { return std::make_unique<CoordinationServiceAgentImpl>(); }
#include "xla/tsl/distributed_runtime/coordination/coordination_service_agent.h" #include <memory> #include <ostream> #include <string> #include <utility> #include <vector> #include "absl/log/check.h" #include "absl/log/log.h" #include "absl/memory/memory.h" #include "absl/status/status.h" #include "absl/time/clock.h" #include "absl/time/time.h" #include "xla/tsl/distributed_runtime/call_options.h" #include "xla/tsl/distributed_runtime/coordination/coordination_client.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/env.h" #include "tsl/platform/status.h" #include "tsl/platform/test.h" #include "tsl/protobuf/coordination_config.pb.h" #include "tsl/protobuf/coordination_service.pb.h" class CoordinationServiceAgentTest : public ::testing::Test { public: void SetUp() override { ON_CALL(*client_, RegisterTaskAsync(_, _, _, _)) .WillByDefault(InvokeArgument<3>(absl::OkStatus())); ON_CALL(*client_, HeartbeatAsync(_, _, _, _)) .WillByDefault(InvokeArgument<3>(absl::OkStatus())); ON_CALL(*client_, ShutdownTaskAsync(_, _, _, _)) .WillByDefault(InvokeArgument<3>(absl::OkStatus())); ON_CALL(*client_, ReportErrorToServiceAsync(_, _, _)) .WillByDefault(InvokeArgument<2>(absl::OkStatus())); ON_CALL(*client_, ResetTaskAsync(_, _, _)) .WillByDefault(InvokeArgument<2>(absl::OkStatus())); ON_CALL(*client_, BarrierAsync(_, _, _)) .WillByDefault(InvokeArgument<2>(absl::OkStatus())); ON_CALL(*client_, GetTaskStateAsync(_, _, _)) .WillByDefault(InvokeArgument<2>(absl::OkStatus())); } // Should be called after mocking service responses, before testing the agent. void InitializeAgent(CoordinationServiceConfig config = {}) { config.set_service_leader("test_leader"); TF_ASSERT_OK(agent_->Initialize( Env::Default(), /*job_name=*/"test_job", /*task_id=*/0, config, std::move(client_), /*error_fn=*/[](absl::Status s) { LOG(ERROR) << "Coordination agent is set to error: " << s; })); } TestCoordinationClient* GetClient() { // InitializeAgent() transfers ownership of the coordination client. CHECK(client_ != nullptr) << "GetClient() was called after InitializeAgent()"; return client_.get(); } protected: std::unique_ptr<CoordinationServiceAgent> agent_ = CreateCoordinationServiceAgent(); std::unique_ptr<TestCoordinationClient> client_ = std::make_unique<TestCoordinationClient>(); }; TEST_F(CoordinationServiceAgentTest, GetOwnTask) { InitializeAgent(); auto result = agent_->GetOwnTask(); TF_ASSERT_OK(result.status()); CoordinatedTask actual_task = *result; // These fields are from the arguments used in InitializeAgent(). CoordinatedTask expected_task; expected_task.set_job_name("test_job"); expected_task.set_task_id(0); EXPECT_EQ(actual_task.job_name(), expected_task.job_name()); EXPECT_EQ(actual_task.task_id(), expected_task.task_id()); }
CoordinationServiceAgentTest_ResetCanBeRetried
xla/tsl/distributed_runtime/coordination/coordination_service_agent_test.cc
CoordinationServiceAgentImpl() = default; ~CoordinationServiceAgentImpl() override { absl::Status s = ShutdownInternal(); VLOG(3) << "Coordination agent dtor failed with status: " << s; } VLOG(3) << "Coordination agent dtor failed with status: " << s; absl::Status CoordinationServiceAgentImpl::Initialize( Env* env, std::string_view job_name, int task_id, const CoordinationServiceConfig& configs, std::unique_ptr<CoordinationClient> leader_client, StatusCallback error_fn) { CoordinatedTask task; task.set_job_name(std::string(job_name)); task.set_task_id(task_id); return Initialize(env, task, configs, std::move(leader_client), error_fn); } absl::Status CoordinationServiceAgentImpl::Initialize( Env* env, const CoordinatedTask& task, const CoordinationServiceConfig& configs, std::unique_ptr<CoordinationClient> leader_client, StatusCallback error_fn) { enabled_usage_metric->GetCell()->Set(true); absl::MutexLock l(&state_mu_); if (state_ != CoordinatedTaskState::TASKSTATE_UNINITIALIZED) { return MakeCoordinationError(absl::FailedPreconditionError( "Coordination service agent has already been initialized.")); } env_ = env; task_ = task; configs_ = configs; if (configs_.service_leader().empty()) { return MakeCoordinationError(absl::InvalidArgumentError( "CoordinationServiceAgent must be initialized with a valid leader.")); } leader_client_ = std::move(leader_client); if (leader_client_ == nullptr) { return MakeCoordinationError(absl::InvalidArgumentError( "CoordinationServiceAgent must have a valid leader client.")); } error_fn_ = error_fn; state_ = CoordinatedTaskState::TASKSTATE_DISCONNECTED; return absl::OkStatus(); } bool CoordinationServiceAgentImpl::IsInitialized() { absl::MutexLock l(&state_mu_); return state_ != CoordinatedTaskState::TASKSTATE_UNINITIALIZED; } bool CoordinationServiceAgentImpl::IsConnected() { absl::MutexLock l(&state_mu_); return state_ == CoordinatedTaskState::TASKSTATE_CONNECTED; } bool CoordinationServiceAgentImpl::IsError() { absl::MutexLock l(&state_mu_); return state_ == CoordinatedTaskState::TASKSTATE_ERROR; } void CoordinationServiceAgentImpl::StopHeartbeat() { { absl::MutexLock l(&heartbeat_thread_shutdown_mu_); shutting_down_ = true; heartbeat_thread_cv_.SignalAll(); } heartbeat_thread_ = nullptr; } absl::Status CoordinationServiceAgentImpl::Connect() { VLOG(3) << "Agent has started trying to Connect()."; { absl::MutexLock l(&state_mu_); if (state_ != CoordinatedTaskState::TASKSTATE_DISCONNECTED) { return MakeCoordinationError(absl::FailedPreconditionError( "Coordination service agent is not in DISCONNECTED state.")); } } absl::Status connect_status = absl::UnknownError("Connection not attempted yet."); RegisterTaskRequest request; *request.mutable_source_task() = task_; request.set_incarnation(incarnation_id_); RegisterTaskResponse response; const int64_t register_timeout = configs_.cluster_register_timeout_in_ms() > 0 ? configs_.cluster_register_timeout_in_ms() : absl::ToInt64Milliseconds(kDefaultClusterRegisterTimeout); const absl::Time deadline = absl::Now() + absl::Milliseconds(register_timeout); int attempt = 0; std::default_random_engine generator; std::uniform_real_distribution<double> distribution(0.0, 1.0); do { ++attempt; CallOptions call_opts; call_opts.SetTimeout(absl::ToInt64Milliseconds(deadline - absl::Now())); absl::Notification n; leader_client_->RegisterTaskAsync( &call_opts, &request, &response, [&](absl::Status s) { if (s.ok()) { leader_incarnation_ = response.leader_incarnation(); { absl::MutexLock l(&state_mu_); state_ = CoordinatedTaskState::TASKSTATE_CONNECTED; } } connect_status = s; n.Notify(); }); n.WaitForNotification(); if (!connect_status.ok()) { // Exponential backoff with jitter. Note we will retry for `init_timeout` // time in total; the `14` here corresponds to an ~16s maximum interval // between connection attempts. const int backoff = 1 << std::min(14, attempt); absl::SleepFor(absl::Milliseconds(backoff * distribution(generator))); } } while (!connect_status.ok() && absl::Now() < deadline && // Retries are attempted for: // 1. RPC errors. // 2. aborted duplicate task registration error - this means that // this task restarted and is trying to reconnect but the service // has not restarted yet. // 3. service has not been enabled - this could happen in the single // client scenario, where the server has been started but the service // cannot be used yet (nullptr). Presumably the service is in the // process of being enabled. (connect_status.GetPayload(CoordinationErrorPayloadKey()) == std::nullopt || absl::IsAborted(connect_status) || absl::IsInternal(connect_status))); if (!connect_status.ok()) { SetError(connect_status); return connect_status; } LOG(INFO) << "Coordination agent has successfully connected."; heartbeat_thread_.reset( env_->StartThread(ThreadOptions(), kHeartbeatThread, [this]() -> void { HeartbeatRequest request; *request.mutable_source_task() = task_; request.set_incarnation(incarnation_id_); HeartbeatResponse response; const int64_t heartbeat_interval_ms = configs_.heartbeat_timeout_in_ms() > 0 ? configs_.heartbeat_timeout_in_ms() / 2 : absl::ToInt64Milliseconds(kDefaultHeartbeatTimeout) / 2; CallOptions call_opts; call_opts.SetTimeout(heartbeat_interval_ms); while (true) { absl::Status status; absl::Notification n; // Heartbeat RPC implementation automatically retries to tolerate // transient network failures. VLOG(10) << "HeartbeatRequest: " << request.DebugString(); leader_client_->HeartbeatAsync(&call_opts, &request, &response, [&](absl::Status s) { status = s; n.Notify(); }); n.WaitForNotification(); VLOG(10) << "HeartbeatResponse: " << status; if (!status.ok()) { // Ignore heartbeat errors and exit thread if shutting down. For // example, the agent may send a heartbeat right after Shutdown() // started, but before StopHeartbeat() and end of Shutdown(). This // results in an unexpected heartbeat error. // Waiting for a second allows us to identify if errors are due to // inflight heartbeats sent during shutdown and can be ignored. absl::SleepFor(absl::Seconds(1)); { absl::MutexLock l(&heartbeat_thread_shutdown_mu_); if (shutting_down_) { return; } } SetError(status); } else if (response.leader_incarnation() != leader_incarnation_) { SetError(MakeCoordinationError( absl::AbortedError("Leader incarnation ID mismatch: the " "coordination leader has restarted."))); } // Send next heartbeat after an interval. { absl::MutexLock l(&heartbeat_thread_shutdown_mu_); heartbeat_thread_cv_.WaitWithTimeout( &heartbeat_thread_shutdown_mu_, absl::Milliseconds(heartbeat_interval_ms)); if (shutting_down_) { return; } } } })); return absl::OkStatus(); } VLOG(3) << "Agent has started trying to Connect()."; &call_opts, &request, &response, [&](absl::Status s) { if (s.ok()) { leader_incarnation_ = response.leader_incarnation(); { absl::MutexLock l(&state_mu_); state_ = CoordinatedTaskState::TASKSTATE_CONNECTED; } } connect_status = s; n.Notify(); }); env_->StartThread(ThreadOptions(), kHeartbeatThread, [this]() -> void { HeartbeatRequest request; *request.mutable_source_task() = task_; request.set_incarnation(incarnation_id_); HeartbeatResponse response; const int64_t heartbeat_interval_ms = configs_.heartbeat_timeout_in_ms() > 0 ? configs_.heartbeat_timeout_in_ms() / 2 : absl::ToInt64Milliseconds(kDefaultHeartbeatTimeout) / 2; CallOptions call_opts; call_opts.SetTimeout(heartbeat_interval_ms); while (true) { absl::Status status; absl::Notification n; // Heartbeat RPC implementation automatically retries to tolerate // transient network failures. VLOG(10) << "HeartbeatRequest: " << request.DebugString(); leader_client_->HeartbeatAsync(&call_opts, &request, &response, [&](absl::Status s) { status = s; n.Notify(); }); n.WaitForNotification(); VLOG(10) << "HeartbeatResponse: " << status; if (!status.ok()) { // Ignore heartbeat errors and exit thread if shutting down. For // example, the agent may send a heartbeat right after Shutdown() // started, but before StopHeartbeat() and end of Shutdown(). This // results in an unexpected heartbeat error. // Waiting for a second allows us to identify if errors are due to // inflight heartbeats sent during shutdown and can be ignored. absl::SleepFor(absl::Seconds(1)); { absl::MutexLock l(&heartbeat_thread_shutdown_mu_); if (shutting_down_) { return; } } SetError(status); } else if (response.leader_incarnation() != leader_incarnation_) { SetError(MakeCoordinationError( absl::AbortedError("Leader incarnation ID mismatch: the " "coordination leader has restarted."))); } // Send next heartbeat after an interval. { absl::MutexLock l(&heartbeat_thread_shutdown_mu_); heartbeat_thread_cv_.WaitWithTimeout( &heartbeat_thread_shutdown_mu_, absl::Milliseconds(heartbeat_interval_ms)); if (shutting_down_) { return; } } } })); VLOG(10) << "HeartbeatRequest: " << request.DebugString(); [&](absl::Status s) { status = s; n.Notify(); }); VLOG(10) << "HeartbeatResponse: " << status; absl::Status CoordinationServiceAgentImpl::WaitForAllTasks( const DeviceInfo& local_devices) { absl::Status agent_running_status = ValidateRunningAgent(); if (!agent_running_status.ok()) { return agent_running_status; } WaitForAllTasksRequest request; *request.mutable_source_task() = task_; *request.mutable_device_info() = local_devices; VLOG(3) << "WaitForAllTasksRequest: " << request.DebugString(); WaitForAllTasksResponse response; absl::Status status; absl::Notification n; leader_client_->WaitForAllTasksAsync(&request, &response, [&](absl::Status s) { status = s; n.Notify(); }); n.WaitForNotification(); if (!status.ok()) { VLOG(3) << "WaitForAllTasksResponse: " << status; SetError(status); return status; } VLOG(3) << "WaitForAllTasksResponse: " << response.DebugString(); cluster_devices_ = response.device_info(); return absl::OkStatus(); } VLOG(3) << "WaitForAllTasksRequest: " << request.DebugString(); [&](absl::Status s) { status = s; n.Notify(); }); VLOG(3) << "WaitForAllTasksResponse: " << status; VLOG(3) << "WaitForAllTasksResponse: " << response.DebugString(); const DeviceInfo& CoordinationServiceAgentImpl::GetClusterDeviceInfo() { return cluster_devices_; } absl::StatusOr<CoordinatedTask> CoordinationServiceAgentImpl::GetOwnTask() { if (!IsInitialized()) { return MakeCoordinationError(absl::FailedPreconditionError( "Agent has not been initialized; we do not " "know the associated task yet.")); } return task_; } CoordinationServiceAgentImpl::GetTaskState( const std::vector<CoordinatedTask>& tasks) { GetTaskStateRequest request; *request.mutable_source_task() = {tasks.begin(), tasks.end()}; GetTaskStateResponse response; absl::Notification n; absl::StatusOr<std::vector<CoordinatedTaskStateInfo>> result; leader_client_->GetTaskStateAsync( &request, &response, [&](const absl::Status& s) { if (s.ok()) { result = std::vector<CoordinatedTaskStateInfo>( std::make_move_iterator(response.task_state().begin()), std::make_move_iterator(response.task_state().end())); } else { result = s; } n.Notify(); }); n.WaitForNotification(); return result; } &request, &response, [&](const absl::Status& s) { if (s.ok()) { result = std::vector<CoordinatedTaskStateInfo>( std::make_move_iterator(response.task_state().begin()), std::make_move_iterator(response.task_state().end())); } else { result = s; } n.Notify(); }); absl::Status CoordinationServiceAgentImpl::ReportError( const absl::Status& error) { { absl::MutexLock l(&state_mu_); if (state_ == CoordinatedTaskState::TASKSTATE_UNINITIALIZED) { return MakeCoordinationError(absl::FailedPreconditionError( "Coordination service agent must be initialized first before " "reporting error.")); } else if (state_ == CoordinatedTaskState::TASKSTATE_ERROR) { return MakeCoordinationError(absl::FailedPreconditionError( "Coordination service agent is already in error state.")); } } SetError(MakeCoordinationError(error, task_, /*is_reported_error=*/true)); LOG(INFO) << "Reporting error to coordination service: " << error; ReportErrorToServiceRequest request; request.set_error_code(error.raw_code()); request.set_error_message(std::string(error.message())); *request.mutable_error_origin() = task_; VLOG(5) << "ReportErrorToServiceRequest: " << request.DebugString(); ReportErrorToServiceResponse response; absl::Notification n; leader_client_->ReportErrorToServiceAsync( &request, &response, [&](absl::Status s) { VLOG(5) << "ReportErrorToServiceResponse: " << s; if (!s.ok()) { LOG(ERROR) << "Encountered another error when reporting error to " "coordination service: " << s << "\nThis is usually caused by an earlier error during " "execution. Check the logs (this task or the leader) for " "an earlier error to debug further."; } n.Notify(); }); n.WaitForNotification(); return absl::OkStatus(); } VLOG(5) << "ReportErrorToServiceRequest: " << request.DebugString(); &request, &response, [&](absl::Status s) { VLOG(5) << "ReportErrorToServiceResponse: " << s; if (!s.ok()) { LOG(ERROR) << "Encountered another error when reporting error to " "coordination service: " << s << "\nThis is usually caused by an earlier error during " "execution. Check the logs (this task or the leader) for " "an earlier error to debug further."; } n.Notify(); }); VLOG(5) << "ReportErrorToServiceResponse: " << s; absl::Status CoordinationServiceAgentImpl::Shutdown() { return ShutdownInternal(); } absl::Status CoordinationServiceAgentImpl::ShutdownInternal() { absl::Status status = absl::OkStatus(); bool is_connected = false; { absl::MutexLock l(&state_mu_); is_connected = state_ == CoordinatedTaskState::TASKSTATE_CONNECTED; } // Disconnect agent from service. if (!configs_.agent_destruction_without_shutdown() && is_connected) { LOG(INFO) << "Coordination agent has initiated Shutdown()."; ShutdownTaskRequest request; *request.mutable_source_task() = task_; ShutdownTaskResponse response; CallOptions call_opts; const int64_t shutdown_timeout = configs_.shutdown_barrier_timeout_in_ms() > 0 ? configs_.shutdown_barrier_timeout_in_ms() : absl::ToInt64Milliseconds(kDefaultShutdownTimeout); call_opts.SetTimeout(shutdown_timeout); absl::Notification n; leader_client_->ShutdownTaskAsync(&call_opts, &request, &response, [&status, &n](absl::Status s) { status = s; n.Notify(); }); n.WaitForNotification(); if (status.ok()) { LOG(INFO) << "Coordination agent has successfully shut down."; } else { LOG(ERROR) << "Failed to disconnect from coordination service with status: " << status << "\nProceeding with agent shutdown anyway. This is usually caused " "by an earlier error during execution. Check the logs (this task " "or the leader) for an earlier error to debug further."; } } // Tear down agent. StopHeartbeat(); { absl::MutexLock l(&state_mu_); if (state_ == CoordinatedTaskState::TASKSTATE_ERROR) { const std::string status_message = absl::StrCat( "Shutdown() was called while coordination agent is in error state, " "implying that distributed execution failed. Note: agent will still " "shutdown anyway. Agent status: ", status_.ToString(), "\nThis is usually caused by an earlier error during execution. " "Check the logs (this task or the leader) for an earlier error to " "debug further."); status = MakeCoordinationError(absl::FailedPreconditionError(status_message)); LOG(ERROR) << status_message; } state_ = CoordinatedTaskState::TASKSTATE_DISCONNECTED; } // Cancel all pending GetKeyValue() RPC calls. cancellation_manager_.StartCancel(); return status; } [&status, &n](absl::Status s) { status = s; n.Notify(); }); absl::Status CoordinationServiceAgentImpl::Reset() { { absl::MutexLock l(&state_mu_); if (state_ != CoordinatedTaskState::TASKSTATE_ERROR) { return MakeCoordinationError(absl::FailedPreconditionError( "Reset() failed: coordination service agent is not in ERROR state.")); } } ResetTaskRequest request; *request.mutable_source_task() = task_; VLOG(3) << "ResetTaskRequest: " << request.DebugString(); ResetTaskResponse response; absl::Status status; absl::Notification n; leader_client_->ResetTaskAsync(&request, &response, [&status, &n](absl::Status s) { status = s; n.Notify(); }); n.WaitForNotification(); VLOG(3) << "ResetTaskResponse: " << status; if (!status.ok()) { return status; } // Reset agent state. StopHeartbeat(); { absl::MutexLock l(&state_mu_); state_ = CoordinatedTaskState::TASKSTATE_DISCONNECTED; } { absl::MutexLock l(&heartbeat_thread_shutdown_mu_); shutting_down_ = false; } LOG(INFO) << "Coordination agent has been reset."; return status; } VLOG(3) << "ResetTaskRequest: " << request.DebugString(); [&status, &n](absl::Status s) { status = s; n.Notify(); }); VLOG(3) << "ResetTaskResponse: " << status; absl::StatusOr<std::string> CoordinationServiceAgentImpl::GetKeyValue( std::string_view key) { return GetKeyValue(key, /*timeout=*/absl::InfiniteDuration()); } absl::StatusOr<std::string> CoordinationServiceAgentImpl::GetKeyValue( std::string_view key, absl::Duration timeout) { auto n = std::make_shared<absl::Notification>(); auto result = std::make_shared<absl::StatusOr<std::string>>(); GetKeyValueAsync( key, [n, result](const absl::StatusOr<std::string>& status_or_value) { *result = status_or_value; n->Notify(); }); bool call_completed_before_timeout = n->WaitForNotificationWithTimeout(timeout); if (!call_completed_before_timeout) { VLOG(3) << "GetKeyValue(" << key << ") timed out after " << timeout; return MakeCoordinationError(absl::DeadlineExceededError(absl::Substitute( "GetKeyValue() timed out with key: $0 and duration: $1", key, absl::FormatDuration(timeout)))); } return *result; } key, [n, result](const absl::StatusOr<std::string>& status_or_value) { *result = status_or_value; n->Notify(); }); VLOG(3) << "GetKeyValue(" << key << ") timed out after " << timeout; std::shared_ptr<CallOptions> CoordinationServiceAgentImpl::GetKeyValueAsync( std::string_view key, StatusOrValueCallback done) { auto request = std::make_shared<GetKeyValueRequest>(); request->set_key(key.data(), key.size()); VLOG(3) << "GetKeyValueRequest: " << request->DebugString(); auto response = std::make_shared<GetKeyValueResponse>(); auto call_opts = std::make_shared<CallOptions>(); const CancellationToken token = cancellation_manager_.get_cancellation_token(); const bool already_cancelled = !cancellation_manager_.RegisterCallback( token, [call_opts]() { call_opts->StartCancel(); }); if (already_cancelled) { done(absl::CancelledError("GetKeyValueAsync() was cancelled.")); return call_opts; } leader_client_->GetKeyValueAsync( call_opts.get(), request.get(), response.get(), [call_opts, request, response, done = std::move(done), &cm = cancellation_manager_, token](const absl::Status& s) { // RPC call has completed (no longer needs to be cancelled if agent is // destroyed). cm.TryDeregisterCallback(token); // Retrieve server response. if (!s.ok()) { done(s); VLOG(3) << "GetKeyValueResponse: " << s; } else { done(response->kv().value()); VLOG(3) << "GetKeyValueResponse: " << response->DebugString(); } }); return call_opts; } VLOG(3) << "GetKeyValueRequest: " << request->DebugString(); [call_opts, request, response, done = std::move(done), &cm = cancellation_manager_, token](const absl::Status& s) { // RPC call has completed (no longer needs to be cancelled if agent is // destroyed). cm.TryDeregisterCallback(token); // Retrieve server response. if (!s.ok()) { done(s); VLOG(3) << "GetKeyValueResponse: " << s; } else { done(response->kv().value()); VLOG(3) << "GetKeyValueResponse: " << response->DebugString(); } }); VLOG(3) << "GetKeyValueResponse: " << s; VLOG(3) << "GetKeyValueResponse: " << response->DebugString(); absl::StatusOr<std::string> CoordinationServiceAgentImpl::TryGetKeyValue( std::string_view key) { absl::Notification n; absl::StatusOr<std::string> result; TryGetKeyValueRequest request; request.set_key(key.data(), key.size()); VLOG(3) << "TryGetKeyValueRequest: " << request.DebugString(); TryGetKeyValueResponse response; leader_client_->TryGetKeyValueAsync( &request, &response, [&](const absl::Status& s) { if (s.ok()) { result = response.kv().value(); VLOG(3) << "TryGetKeyValueResponse: " << result.value(); } else { result = s; VLOG(3) << "TryGetKeyValueResponse: " << s; } n.Notify(); }); n.WaitForNotification(); return result; } VLOG(3) << "TryGetKeyValueRequest: " << request.DebugString(); &request, &response, [&](const absl::Status& s) { if (s.ok()) { result = response.kv().value(); VLOG(3) << "TryGetKeyValueResponse: " << result.value(); } else { result = s; VLOG(3) << "TryGetKeyValueResponse: " << s; } n.Notify(); }); VLOG(3) << "TryGetKeyValueResponse: " << result.value(); VLOG(3) << "TryGetKeyValueResponse: " << s; CoordinationServiceAgentImpl::GetKeyValueDir(std::string_view key) { absl::Notification n; absl::StatusOr<std::vector<KeyValueEntry>> result; GetKeyValueDirAsync( key, [&n, &result]( absl::StatusOr<std::vector<KeyValueEntry>> status_or_value) { result = std::move(status_or_value); n.Notify(); }); n.WaitForNotification(); return result; } key, [&n, &result]( absl::StatusOr<std::vector<KeyValueEntry>> status_or_value) { result = std::move(status_or_value); n.Notify(); }); void CoordinationServiceAgentImpl::GetKeyValueDirAsync( std::string_view key, StatusOrValueDirCallback done) { auto request = std::make_shared<GetKeyValueDirRequest>(); request->set_directory_key(key.data(), key.size()); VLOG(3) << "GetKeyValueDirRequest: " << request->DebugString(); auto response = std::make_shared<GetKeyValueDirResponse>(); leader_client_->GetKeyValueDirAsync( request.get(), response.get(), [request, response, done = std::move(done)](const absl::Status& s) { if (!s.ok()) { done(s); VLOG(3) << "GetKeyValueDirResponse: " << s; } else { VLOG(3) << "GetKeyValueDirResponse: " << response->DebugString(); std::vector<KeyValueEntry> kv_in_directory = { std::make_move_iterator(response->kv().begin()), std::make_move_iterator(response->kv().end())}; done(kv_in_directory); } }); } VLOG(3) << "GetKeyValueDirRequest: " << request->DebugString(); [request, response, done = std::move(done)](const absl::Status& s) { if (!s.ok()) { done(s); VLOG(3) << "GetKeyValueDirResponse: " << s; } else { VLOG(3) << "GetKeyValueDirResponse: " << response->DebugString(); std::vector<KeyValueEntry> kv_in_directory = { std::make_move_iterator(response->kv().begin()), std::make_move_iterator(response->kv().end())}; done(kv_in_directory); } }); VLOG(3) << "GetKeyValueDirResponse: " << s; VLOG(3) << "GetKeyValueDirResponse: " << response->DebugString(); absl::Status CoordinationServiceAgentImpl::InsertKeyValue( std::string_view key, std::string_view value) { return InsertKeyValue(key, value, /*allow_overwrite=*/false); } absl::Status CoordinationServiceAgentImpl::InsertKeyValue( std::string_view key, std::string_view value, bool allow_overwrite) { InsertKeyValueRequest request; request.mutable_kv()->set_key(key.data(), key.size()); request.mutable_kv()->set_value(value.data(), value.size()); request.set_allow_overwrite(allow_overwrite); VLOG(3) << "InsertKeyValueRequest: " << request.DebugString(); InsertKeyValueResponse response; absl::Status status; absl::Notification n; leader_client_->InsertKeyValueAsync(&request, &response, [&](absl::Status s) { status = s; n.Notify(); }); n.WaitForNotification(); VLOG(3) << "InsertKeyValueResponse: " << status; return status; } VLOG(3) << "InsertKeyValueRequest: " << request.DebugString(); leader_client_->InsertKeyValueAsync(&request, &response, [&](absl::Status s) { status = s; n.Notify(); }); VLOG(3) << "InsertKeyValueResponse: " << status; absl::Status CoordinationServiceAgentImpl::DeleteKeyValue( std::string_view key) { DeleteKeyValueRequest request; request.set_key(key.data(), key.size()); request.set_is_directory(true); VLOG(3) << "DeleteKeyValueRequest: " << request.DebugString(); DeleteKeyValueResponse response; absl::Status status; absl::Notification n; leader_client_->DeleteKeyValueAsync(&request, &response, [&](absl::Status s) { status = s; n.Notify(); }); n.WaitForNotification(); VLOG(3) << "DeleteKeyValueResponse " << status; return absl::OkStatus(); } VLOG(3) << "DeleteKeyValueRequest: " << request.DebugString(); leader_client_->DeleteKeyValueAsync(&request, &response, [&](absl::Status s) { status = s; n.Notify(); }); VLOG(3) << "DeleteKeyValueResponse " << status; absl::Status CoordinationServiceAgentImpl::UpdateKeyValue( std::string_view key, std::string_view value) { return MakeCoordinationError(absl::UnimplementedError( "CoordinationServiceAgent::UpdateKeyValue is not implemented.")); } absl::Status CoordinationServiceAgentImpl::StartWatchKey( std::string_view key, CoordinationServiceAgentImpl::ChangedKeyValuesCallback on_change) { return MakeCoordinationError(absl::UnimplementedError( "CoordinationServiceAgent::StartWatchKey is not implemented.")); } absl::Status CoordinationServiceAgentImpl::StopWatchKey(std::string_view key) { return MakeCoordinationError(absl::UnimplementedError( "CoordinationServiceAgent::StopWatchKey is not implemented.")); } void CoordinationServiceAgentImpl::SetError(const absl::Status& error) { assert(!error.ok()); absl::MutexLock l(&state_mu_); if (state_ == CoordinatedTaskState::TASKSTATE_ERROR) return; LOG(ERROR) << "Coordination agent is set to ERROR: " << error; state_ = CoordinatedTaskState::TASKSTATE_ERROR; status_ = error; error_fn_(error); } absl::Status CoordinationServiceAgentImpl::ActivateWatch( std::string_view key, const std::map<std::string, std::string>& kvs) { return MakeCoordinationError(absl::UnimplementedError( "CoordinationServiceAgent::ActivateWatch is not implemented.")); } absl::Status CoordinationServiceAgentImpl::WaitAtBarrier( std::string_view barrier_id, absl::Duration timeout, const std::vector<CoordinatedTask>& tasks) { absl::Status status; absl::Notification n; WaitAtBarrierAsync(barrier_id, timeout, tasks, [&](absl::Status s) { status = s; n.Notify(); }); n.WaitForNotification(); return status; } WaitAtBarrierAsync(barrier_id, timeout, tasks, [&](absl::Status s) { status = s; n.Notify(); }); void CoordinationServiceAgentImpl::WaitAtBarrierAsync( std::string_view barrier_id, absl::Duration timeout, const std::vector<CoordinatedTask>& tasks, StatusCallback done) { absl::Status agent_running_status = ValidateRunningAgent(/*allow_disconnected=*/true); if (!agent_running_status.ok()) { done(agent_running_status); return; } { absl::MutexLock l(&state_mu_); auto [it, inserted] = used_barrier_ids_.insert(std::string(barrier_id)); if (!inserted) { done(absl::FailedPreconditionError(absl::StrCat( "WaitAtBarrier() should not be called with the same id more than " "once. Barrier id: ", barrier_id))); return; } } auto request = std::make_shared<BarrierRequest>(); auto response = std::make_shared<BarrierResponse>(); request->set_barrier_id(std::string(barrier_id)); request->set_barrier_timeout_in_ms(timeout / absl::Milliseconds(1)); *request->mutable_source_task() = task_; *request->mutable_tasks() = {tasks.begin(), tasks.end()}; VLOG(3) << "WaitAtBarrierRequest: " << request->DebugString(); leader_client_->BarrierAsync( request.get(), response.get(), [request, response, done = std::move(done)](const absl::Status& s) { done(s); VLOG(3) << "WaitAtBarrierResponse: " << s; }); } VLOG(3) << "WaitAtBarrierRequest: " << request->DebugString(); [request, response, done = std::move(done)](const absl::Status& s) { done(s); VLOG(3) << "WaitAtBarrierResponse: " << s; }); VLOG(3) << "WaitAtBarrierResponse: " << s; absl::Status CoordinationServiceAgentImpl::CancelBarrier( std::string_view barrier_id) { absl::Status status; absl::Notification n; CancelBarrierAsync(barrier_id, [&](const absl::Status& s) { status = s; n.Notify(); }); n.WaitForNotification(); return status; } CancelBarrierAsync(barrier_id, [&](const absl::Status& s) { status = s; n.Notify(); }); void CoordinationServiceAgentImpl::CancelBarrierAsync( std::string_view barrier_id, StatusCallback done) { absl::Status agent_running_status = ValidateRunningAgent(/*allow_disconnected=*/true); if (!agent_running_status.ok()) { done(agent_running_status); return; } auto request = std::make_shared<CancelBarrierRequest>(); auto response = std::make_shared<CancelBarrierResponse>(); request->set_barrier_id(std::string(barrier_id)); *request->mutable_source_task() = task_; VLOG(3) << "CancelBarrierRequest: " << request->DebugString(); leader_client_->CancelBarrierAsync( request.get(), response.get(), [request, response, done = std::move(done)](const absl::Status& s) { done(s); VLOG(3) << "CancelBarrierResponse: " << s; }); } VLOG(3) << "CancelBarrierRequest: " << request->DebugString(); [request, response, done = std::move(done)](const absl::Status& s) { done(s); VLOG(3) << "CancelBarrierResponse: " << s; }); VLOG(3) << "CancelBarrierResponse: " << s; absl::Status CoordinationServiceAgentImpl::ValidateRunningAgent( bool allow_disconnected) { absl::MutexLock l(&state_mu_); switch (state_) { case CoordinatedTaskState::TASKSTATE_CONNECTED: return absl::OkStatus(); case CoordinatedTaskState::TASKSTATE_UNINITIALIZED: return MakeCoordinationError(absl::FailedPreconditionError( "Agent must be in CONNECTED state. It is currently UNINITIALIZED.")); case CoordinatedTaskState::TASKSTATE_DISCONNECTED: if (allow_disconnected) return absl::OkStatus(); return MakeCoordinationError(absl::FailedPreconditionError( "Agent must be in CONNECTED state. It is currently DISCONNECTED.")); case CoordinatedTaskState::TASKSTATE_ERROR: return MakeCoordinationError(absl::FailedPreconditionError( "Agent must be in CONNECTED state. It is currently in ERROR.")); default: return MakeCoordinationError(absl::FailedPreconditionError(absl::StrCat( "Agent is not in CONNECTED state. Current state: ", state_))); } } absl::StatusOr<Env*> CoordinationServiceAgentImpl::GetEnv() { if (!IsInitialized()) { return MakeCoordinationError(absl::FailedPreconditionError( "Coordination service agent has not been initialized.")); } if (env_ == nullptr) { return MakeCoordinationError( absl::FailedPreconditionError("Coordination service agent was not " "initialized with a valid Env* object.")); } return env_; } std::unique_ptr<CoordinationServiceAgent> CreateCoordinationServiceAgent() { return std::make_unique<CoordinationServiceAgentImpl>(); }
#include "xla/tsl/distributed_runtime/coordination/coordination_service_agent.h" #include <memory> #include <ostream> #include <string> #include <utility> #include <vector> #include "absl/log/check.h" #include "absl/log/log.h" #include "absl/memory/memory.h" #include "absl/status/status.h" #include "absl/time/clock.h" #include "absl/time/time.h" #include "xla/tsl/distributed_runtime/call_options.h" #include "xla/tsl/distributed_runtime/coordination/coordination_client.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/env.h" #include "tsl/platform/status.h" #include "tsl/platform/test.h" #include "tsl/protobuf/coordination_config.pb.h" #include "tsl/protobuf/coordination_service.pb.h" class CoordinationServiceAgentTest : public ::testing::Test { public: void SetUp() override { ON_CALL(*client_, RegisterTaskAsync(_, _, _, _)) .WillByDefault(InvokeArgument<3>(absl::OkStatus())); ON_CALL(*client_, HeartbeatAsync(_, _, _, _)) .WillByDefault(InvokeArgument<3>(absl::OkStatus())); ON_CALL(*client_, ShutdownTaskAsync(_, _, _, _)) .WillByDefault(InvokeArgument<3>(absl::OkStatus())); ON_CALL(*client_, ReportErrorToServiceAsync(_, _, _)) .WillByDefault(InvokeArgument<2>(absl::OkStatus())); ON_CALL(*client_, ResetTaskAsync(_, _, _)) .WillByDefault(InvokeArgument<2>(absl::OkStatus())); ON_CALL(*client_, BarrierAsync(_, _, _)) .WillByDefault(InvokeArgument<2>(absl::OkStatus())); ON_CALL(*client_, GetTaskStateAsync(_, _, _)) .WillByDefault(InvokeArgument<2>(absl::OkStatus())); } // Should be called after mocking service responses, before testing the agent. void InitializeAgent(CoordinationServiceConfig config = {}) { config.set_service_leader("test_leader"); TF_ASSERT_OK(agent_->Initialize( Env::Default(), /*job_name=*/"test_job", /*task_id=*/0, config, std::move(client_), /*error_fn=*/[](absl::Status s) { LOG(ERROR) << "Coordination agent is set to error: " << s; })); } TestCoordinationClient* GetClient() { // InitializeAgent() transfers ownership of the coordination client. CHECK(client_ != nullptr) << "GetClient() was called after InitializeAgent()"; return client_.get(); } protected: std::unique_ptr<CoordinationServiceAgent> agent_ = CreateCoordinationServiceAgent(); std::unique_ptr<TestCoordinationClient> client_ = std::make_unique<TestCoordinationClient>(); }; TEST_F(CoordinationServiceAgentTest, ResetCanBeRetried) { // Mock reset error failing for the first time. EXPECT_CALL(*GetClient(), ResetTaskAsync(_, _, _)) .WillOnce(InvokeArgument<2>(absl::InternalError("Reset error"))) .WillOnce(InvokeArgument<2>(absl::OkStatus())); // Connect coordination agent and set it to error. InitializeAgent(); TF_ASSERT_OK(agent_->Connect()); TF_ASSERT_OK(agent_->ReportError(absl::InternalError("Test Error."))); // Reset error fails for the first time. absl::Status reset_status = agent_->Reset(); EXPECT_TRUE(absl::IsInternal(reset_status)); // Agent should be able to attempt resetting again. TF_ASSERT_OK(agent_->Reset()); // Agent should be able to reconnect to the service after resetting. TF_EXPECT_OK(agent_->Connect()); }
CoordinationServiceAgentTest_ShutdownInErrorShouldReturnError
xla/tsl/distributed_runtime/coordination/coordination_service_agent_test.cc
CoordinationServiceAgentImpl() = default; ~CoordinationServiceAgentImpl() override { absl::Status s = ShutdownInternal(); VLOG(3) << "Coordination agent dtor failed with status: " << s; } VLOG(3) << "Coordination agent dtor failed with status: " << s; absl::Status CoordinationServiceAgentImpl::Initialize( Env* env, std::string_view job_name, int task_id, const CoordinationServiceConfig& configs, std::unique_ptr<CoordinationClient> leader_client, StatusCallback error_fn) { CoordinatedTask task; task.set_job_name(std::string(job_name)); task.set_task_id(task_id); return Initialize(env, task, configs, std::move(leader_client), error_fn); } absl::Status CoordinationServiceAgentImpl::Initialize( Env* env, const CoordinatedTask& task, const CoordinationServiceConfig& configs, std::unique_ptr<CoordinationClient> leader_client, StatusCallback error_fn) { enabled_usage_metric->GetCell()->Set(true); absl::MutexLock l(&state_mu_); if (state_ != CoordinatedTaskState::TASKSTATE_UNINITIALIZED) { return MakeCoordinationError(absl::FailedPreconditionError( "Coordination service agent has already been initialized.")); } env_ = env; task_ = task; configs_ = configs; if (configs_.service_leader().empty()) { return MakeCoordinationError(absl::InvalidArgumentError( "CoordinationServiceAgent must be initialized with a valid leader.")); } leader_client_ = std::move(leader_client); if (leader_client_ == nullptr) { return MakeCoordinationError(absl::InvalidArgumentError( "CoordinationServiceAgent must have a valid leader client.")); } error_fn_ = error_fn; state_ = CoordinatedTaskState::TASKSTATE_DISCONNECTED; return absl::OkStatus(); } bool CoordinationServiceAgentImpl::IsInitialized() { absl::MutexLock l(&state_mu_); return state_ != CoordinatedTaskState::TASKSTATE_UNINITIALIZED; } bool CoordinationServiceAgentImpl::IsConnected() { absl::MutexLock l(&state_mu_); return state_ == CoordinatedTaskState::TASKSTATE_CONNECTED; } bool CoordinationServiceAgentImpl::IsError() { absl::MutexLock l(&state_mu_); return state_ == CoordinatedTaskState::TASKSTATE_ERROR; } void CoordinationServiceAgentImpl::StopHeartbeat() { { absl::MutexLock l(&heartbeat_thread_shutdown_mu_); shutting_down_ = true; heartbeat_thread_cv_.SignalAll(); } heartbeat_thread_ = nullptr; } absl::Status CoordinationServiceAgentImpl::Connect() { VLOG(3) << "Agent has started trying to Connect()."; { absl::MutexLock l(&state_mu_); if (state_ != CoordinatedTaskState::TASKSTATE_DISCONNECTED) { return MakeCoordinationError(absl::FailedPreconditionError( "Coordination service agent is not in DISCONNECTED state.")); } } absl::Status connect_status = absl::UnknownError("Connection not attempted yet."); RegisterTaskRequest request; *request.mutable_source_task() = task_; request.set_incarnation(incarnation_id_); RegisterTaskResponse response; const int64_t register_timeout = configs_.cluster_register_timeout_in_ms() > 0 ? configs_.cluster_register_timeout_in_ms() : absl::ToInt64Milliseconds(kDefaultClusterRegisterTimeout); const absl::Time deadline = absl::Now() + absl::Milliseconds(register_timeout); int attempt = 0; std::default_random_engine generator; std::uniform_real_distribution<double> distribution(0.0, 1.0); do { ++attempt; CallOptions call_opts; call_opts.SetTimeout(absl::ToInt64Milliseconds(deadline - absl::Now())); absl::Notification n; leader_client_->RegisterTaskAsync( &call_opts, &request, &response, [&](absl::Status s) { if (s.ok()) { leader_incarnation_ = response.leader_incarnation(); { absl::MutexLock l(&state_mu_); state_ = CoordinatedTaskState::TASKSTATE_CONNECTED; } } connect_status = s; n.Notify(); }); n.WaitForNotification(); if (!connect_status.ok()) { // Exponential backoff with jitter. Note we will retry for `init_timeout` // time in total; the `14` here corresponds to an ~16s maximum interval // between connection attempts. const int backoff = 1 << std::min(14, attempt); absl::SleepFor(absl::Milliseconds(backoff * distribution(generator))); } } while (!connect_status.ok() && absl::Now() < deadline && // Retries are attempted for: // 1. RPC errors. // 2. aborted duplicate task registration error - this means that // this task restarted and is trying to reconnect but the service // has not restarted yet. // 3. service has not been enabled - this could happen in the single // client scenario, where the server has been started but the service // cannot be used yet (nullptr). Presumably the service is in the // process of being enabled. (connect_status.GetPayload(CoordinationErrorPayloadKey()) == std::nullopt || absl::IsAborted(connect_status) || absl::IsInternal(connect_status))); if (!connect_status.ok()) { SetError(connect_status); return connect_status; } LOG(INFO) << "Coordination agent has successfully connected."; heartbeat_thread_.reset( env_->StartThread(ThreadOptions(), kHeartbeatThread, [this]() -> void { HeartbeatRequest request; *request.mutable_source_task() = task_; request.set_incarnation(incarnation_id_); HeartbeatResponse response; const int64_t heartbeat_interval_ms = configs_.heartbeat_timeout_in_ms() > 0 ? configs_.heartbeat_timeout_in_ms() / 2 : absl::ToInt64Milliseconds(kDefaultHeartbeatTimeout) / 2; CallOptions call_opts; call_opts.SetTimeout(heartbeat_interval_ms); while (true) { absl::Status status; absl::Notification n; // Heartbeat RPC implementation automatically retries to tolerate // transient network failures. VLOG(10) << "HeartbeatRequest: " << request.DebugString(); leader_client_->HeartbeatAsync(&call_opts, &request, &response, [&](absl::Status s) { status = s; n.Notify(); }); n.WaitForNotification(); VLOG(10) << "HeartbeatResponse: " << status; if (!status.ok()) { // Ignore heartbeat errors and exit thread if shutting down. For // example, the agent may send a heartbeat right after Shutdown() // started, but before StopHeartbeat() and end of Shutdown(). This // results in an unexpected heartbeat error. // Waiting for a second allows us to identify if errors are due to // inflight heartbeats sent during shutdown and can be ignored. absl::SleepFor(absl::Seconds(1)); { absl::MutexLock l(&heartbeat_thread_shutdown_mu_); if (shutting_down_) { return; } } SetError(status); } else if (response.leader_incarnation() != leader_incarnation_) { SetError(MakeCoordinationError( absl::AbortedError("Leader incarnation ID mismatch: the " "coordination leader has restarted."))); } // Send next heartbeat after an interval. { absl::MutexLock l(&heartbeat_thread_shutdown_mu_); heartbeat_thread_cv_.WaitWithTimeout( &heartbeat_thread_shutdown_mu_, absl::Milliseconds(heartbeat_interval_ms)); if (shutting_down_) { return; } } } })); return absl::OkStatus(); } VLOG(3) << "Agent has started trying to Connect()."; &call_opts, &request, &response, [&](absl::Status s) { if (s.ok()) { leader_incarnation_ = response.leader_incarnation(); { absl::MutexLock l(&state_mu_); state_ = CoordinatedTaskState::TASKSTATE_CONNECTED; } } connect_status = s; n.Notify(); }); env_->StartThread(ThreadOptions(), kHeartbeatThread, [this]() -> void { HeartbeatRequest request; *request.mutable_source_task() = task_; request.set_incarnation(incarnation_id_); HeartbeatResponse response; const int64_t heartbeat_interval_ms = configs_.heartbeat_timeout_in_ms() > 0 ? configs_.heartbeat_timeout_in_ms() / 2 : absl::ToInt64Milliseconds(kDefaultHeartbeatTimeout) / 2; CallOptions call_opts; call_opts.SetTimeout(heartbeat_interval_ms); while (true) { absl::Status status; absl::Notification n; // Heartbeat RPC implementation automatically retries to tolerate // transient network failures. VLOG(10) << "HeartbeatRequest: " << request.DebugString(); leader_client_->HeartbeatAsync(&call_opts, &request, &response, [&](absl::Status s) { status = s; n.Notify(); }); n.WaitForNotification(); VLOG(10) << "HeartbeatResponse: " << status; if (!status.ok()) { // Ignore heartbeat errors and exit thread if shutting down. For // example, the agent may send a heartbeat right after Shutdown() // started, but before StopHeartbeat() and end of Shutdown(). This // results in an unexpected heartbeat error. // Waiting for a second allows us to identify if errors are due to // inflight heartbeats sent during shutdown and can be ignored. absl::SleepFor(absl::Seconds(1)); { absl::MutexLock l(&heartbeat_thread_shutdown_mu_); if (shutting_down_) { return; } } SetError(status); } else if (response.leader_incarnation() != leader_incarnation_) { SetError(MakeCoordinationError( absl::AbortedError("Leader incarnation ID mismatch: the " "coordination leader has restarted."))); } // Send next heartbeat after an interval. { absl::MutexLock l(&heartbeat_thread_shutdown_mu_); heartbeat_thread_cv_.WaitWithTimeout( &heartbeat_thread_shutdown_mu_, absl::Milliseconds(heartbeat_interval_ms)); if (shutting_down_) { return; } } } })); VLOG(10) << "HeartbeatRequest: " << request.DebugString(); [&](absl::Status s) { status = s; n.Notify(); }); VLOG(10) << "HeartbeatResponse: " << status; absl::Status CoordinationServiceAgentImpl::WaitForAllTasks( const DeviceInfo& local_devices) { absl::Status agent_running_status = ValidateRunningAgent(); if (!agent_running_status.ok()) { return agent_running_status; } WaitForAllTasksRequest request; *request.mutable_source_task() = task_; *request.mutable_device_info() = local_devices; VLOG(3) << "WaitForAllTasksRequest: " << request.DebugString(); WaitForAllTasksResponse response; absl::Status status; absl::Notification n; leader_client_->WaitForAllTasksAsync(&request, &response, [&](absl::Status s) { status = s; n.Notify(); }); n.WaitForNotification(); if (!status.ok()) { VLOG(3) << "WaitForAllTasksResponse: " << status; SetError(status); return status; } VLOG(3) << "WaitForAllTasksResponse: " << response.DebugString(); cluster_devices_ = response.device_info(); return absl::OkStatus(); } VLOG(3) << "WaitForAllTasksRequest: " << request.DebugString(); [&](absl::Status s) { status = s; n.Notify(); }); VLOG(3) << "WaitForAllTasksResponse: " << status; VLOG(3) << "WaitForAllTasksResponse: " << response.DebugString(); const DeviceInfo& CoordinationServiceAgentImpl::GetClusterDeviceInfo() { return cluster_devices_; } absl::StatusOr<CoordinatedTask> CoordinationServiceAgentImpl::GetOwnTask() { if (!IsInitialized()) { return MakeCoordinationError(absl::FailedPreconditionError( "Agent has not been initialized; we do not " "know the associated task yet.")); } return task_; } CoordinationServiceAgentImpl::GetTaskState( const std::vector<CoordinatedTask>& tasks) { GetTaskStateRequest request; *request.mutable_source_task() = {tasks.begin(), tasks.end()}; GetTaskStateResponse response; absl::Notification n; absl::StatusOr<std::vector<CoordinatedTaskStateInfo>> result; leader_client_->GetTaskStateAsync( &request, &response, [&](const absl::Status& s) { if (s.ok()) { result = std::vector<CoordinatedTaskStateInfo>( std::make_move_iterator(response.task_state().begin()), std::make_move_iterator(response.task_state().end())); } else { result = s; } n.Notify(); }); n.WaitForNotification(); return result; } &request, &response, [&](const absl::Status& s) { if (s.ok()) { result = std::vector<CoordinatedTaskStateInfo>( std::make_move_iterator(response.task_state().begin()), std::make_move_iterator(response.task_state().end())); } else { result = s; } n.Notify(); }); absl::Status CoordinationServiceAgentImpl::ReportError( const absl::Status& error) { { absl::MutexLock l(&state_mu_); if (state_ == CoordinatedTaskState::TASKSTATE_UNINITIALIZED) { return MakeCoordinationError(absl::FailedPreconditionError( "Coordination service agent must be initialized first before " "reporting error.")); } else if (state_ == CoordinatedTaskState::TASKSTATE_ERROR) { return MakeCoordinationError(absl::FailedPreconditionError( "Coordination service agent is already in error state.")); } } SetError(MakeCoordinationError(error, task_, /*is_reported_error=*/true)); LOG(INFO) << "Reporting error to coordination service: " << error; ReportErrorToServiceRequest request; request.set_error_code(error.raw_code()); request.set_error_message(std::string(error.message())); *request.mutable_error_origin() = task_; VLOG(5) << "ReportErrorToServiceRequest: " << request.DebugString(); ReportErrorToServiceResponse response; absl::Notification n; leader_client_->ReportErrorToServiceAsync( &request, &response, [&](absl::Status s) { VLOG(5) << "ReportErrorToServiceResponse: " << s; if (!s.ok()) { LOG(ERROR) << "Encountered another error when reporting error to " "coordination service: " << s << "\nThis is usually caused by an earlier error during " "execution. Check the logs (this task or the leader) for " "an earlier error to debug further."; } n.Notify(); }); n.WaitForNotification(); return absl::OkStatus(); } VLOG(5) << "ReportErrorToServiceRequest: " << request.DebugString(); &request, &response, [&](absl::Status s) { VLOG(5) << "ReportErrorToServiceResponse: " << s; if (!s.ok()) { LOG(ERROR) << "Encountered another error when reporting error to " "coordination service: " << s << "\nThis is usually caused by an earlier error during " "execution. Check the logs (this task or the leader) for " "an earlier error to debug further."; } n.Notify(); }); VLOG(5) << "ReportErrorToServiceResponse: " << s; absl::Status CoordinationServiceAgentImpl::Shutdown() { return ShutdownInternal(); } absl::Status CoordinationServiceAgentImpl::ShutdownInternal() { absl::Status status = absl::OkStatus(); bool is_connected = false; { absl::MutexLock l(&state_mu_); is_connected = state_ == CoordinatedTaskState::TASKSTATE_CONNECTED; } // Disconnect agent from service. if (!configs_.agent_destruction_without_shutdown() && is_connected) { LOG(INFO) << "Coordination agent has initiated Shutdown()."; ShutdownTaskRequest request; *request.mutable_source_task() = task_; ShutdownTaskResponse response; CallOptions call_opts; const int64_t shutdown_timeout = configs_.shutdown_barrier_timeout_in_ms() > 0 ? configs_.shutdown_barrier_timeout_in_ms() : absl::ToInt64Milliseconds(kDefaultShutdownTimeout); call_opts.SetTimeout(shutdown_timeout); absl::Notification n; leader_client_->ShutdownTaskAsync(&call_opts, &request, &response, [&status, &n](absl::Status s) { status = s; n.Notify(); }); n.WaitForNotification(); if (status.ok()) { LOG(INFO) << "Coordination agent has successfully shut down."; } else { LOG(ERROR) << "Failed to disconnect from coordination service with status: " << status << "\nProceeding with agent shutdown anyway. This is usually caused " "by an earlier error during execution. Check the logs (this task " "or the leader) for an earlier error to debug further."; } } // Tear down agent. StopHeartbeat(); { absl::MutexLock l(&state_mu_); if (state_ == CoordinatedTaskState::TASKSTATE_ERROR) { const std::string status_message = absl::StrCat( "Shutdown() was called while coordination agent is in error state, " "implying that distributed execution failed. Note: agent will still " "shutdown anyway. Agent status: ", status_.ToString(), "\nThis is usually caused by an earlier error during execution. " "Check the logs (this task or the leader) for an earlier error to " "debug further."); status = MakeCoordinationError(absl::FailedPreconditionError(status_message)); LOG(ERROR) << status_message; } state_ = CoordinatedTaskState::TASKSTATE_DISCONNECTED; } // Cancel all pending GetKeyValue() RPC calls. cancellation_manager_.StartCancel(); return status; } [&status, &n](absl::Status s) { status = s; n.Notify(); }); absl::Status CoordinationServiceAgentImpl::Reset() { { absl::MutexLock l(&state_mu_); if (state_ != CoordinatedTaskState::TASKSTATE_ERROR) { return MakeCoordinationError(absl::FailedPreconditionError( "Reset() failed: coordination service agent is not in ERROR state.")); } } ResetTaskRequest request; *request.mutable_source_task() = task_; VLOG(3) << "ResetTaskRequest: " << request.DebugString(); ResetTaskResponse response; absl::Status status; absl::Notification n; leader_client_->ResetTaskAsync(&request, &response, [&status, &n](absl::Status s) { status = s; n.Notify(); }); n.WaitForNotification(); VLOG(3) << "ResetTaskResponse: " << status; if (!status.ok()) { return status; } // Reset agent state. StopHeartbeat(); { absl::MutexLock l(&state_mu_); state_ = CoordinatedTaskState::TASKSTATE_DISCONNECTED; } { absl::MutexLock l(&heartbeat_thread_shutdown_mu_); shutting_down_ = false; } LOG(INFO) << "Coordination agent has been reset."; return status; } VLOG(3) << "ResetTaskRequest: " << request.DebugString(); [&status, &n](absl::Status s) { status = s; n.Notify(); }); VLOG(3) << "ResetTaskResponse: " << status; absl::StatusOr<std::string> CoordinationServiceAgentImpl::GetKeyValue( std::string_view key) { return GetKeyValue(key, /*timeout=*/absl::InfiniteDuration()); } absl::StatusOr<std::string> CoordinationServiceAgentImpl::GetKeyValue( std::string_view key, absl::Duration timeout) { auto n = std::make_shared<absl::Notification>(); auto result = std::make_shared<absl::StatusOr<std::string>>(); GetKeyValueAsync( key, [n, result](const absl::StatusOr<std::string>& status_or_value) { *result = status_or_value; n->Notify(); }); bool call_completed_before_timeout = n->WaitForNotificationWithTimeout(timeout); if (!call_completed_before_timeout) { VLOG(3) << "GetKeyValue(" << key << ") timed out after " << timeout; return MakeCoordinationError(absl::DeadlineExceededError(absl::Substitute( "GetKeyValue() timed out with key: $0 and duration: $1", key, absl::FormatDuration(timeout)))); } return *result; } key, [n, result](const absl::StatusOr<std::string>& status_or_value) { *result = status_or_value; n->Notify(); }); VLOG(3) << "GetKeyValue(" << key << ") timed out after " << timeout; std::shared_ptr<CallOptions> CoordinationServiceAgentImpl::GetKeyValueAsync( std::string_view key, StatusOrValueCallback done) { auto request = std::make_shared<GetKeyValueRequest>(); request->set_key(key.data(), key.size()); VLOG(3) << "GetKeyValueRequest: " << request->DebugString(); auto response = std::make_shared<GetKeyValueResponse>(); auto call_opts = std::make_shared<CallOptions>(); const CancellationToken token = cancellation_manager_.get_cancellation_token(); const bool already_cancelled = !cancellation_manager_.RegisterCallback( token, [call_opts]() { call_opts->StartCancel(); }); if (already_cancelled) { done(absl::CancelledError("GetKeyValueAsync() was cancelled.")); return call_opts; } leader_client_->GetKeyValueAsync( call_opts.get(), request.get(), response.get(), [call_opts, request, response, done = std::move(done), &cm = cancellation_manager_, token](const absl::Status& s) { // RPC call has completed (no longer needs to be cancelled if agent is // destroyed). cm.TryDeregisterCallback(token); // Retrieve server response. if (!s.ok()) { done(s); VLOG(3) << "GetKeyValueResponse: " << s; } else { done(response->kv().value()); VLOG(3) << "GetKeyValueResponse: " << response->DebugString(); } }); return call_opts; } VLOG(3) << "GetKeyValueRequest: " << request->DebugString(); [call_opts, request, response, done = std::move(done), &cm = cancellation_manager_, token](const absl::Status& s) { // RPC call has completed (no longer needs to be cancelled if agent is // destroyed). cm.TryDeregisterCallback(token); // Retrieve server response. if (!s.ok()) { done(s); VLOG(3) << "GetKeyValueResponse: " << s; } else { done(response->kv().value()); VLOG(3) << "GetKeyValueResponse: " << response->DebugString(); } }); VLOG(3) << "GetKeyValueResponse: " << s; VLOG(3) << "GetKeyValueResponse: " << response->DebugString(); absl::StatusOr<std::string> CoordinationServiceAgentImpl::TryGetKeyValue( std::string_view key) { absl::Notification n; absl::StatusOr<std::string> result; TryGetKeyValueRequest request; request.set_key(key.data(), key.size()); VLOG(3) << "TryGetKeyValueRequest: " << request.DebugString(); TryGetKeyValueResponse response; leader_client_->TryGetKeyValueAsync( &request, &response, [&](const absl::Status& s) { if (s.ok()) { result = response.kv().value(); VLOG(3) << "TryGetKeyValueResponse: " << result.value(); } else { result = s; VLOG(3) << "TryGetKeyValueResponse: " << s; } n.Notify(); }); n.WaitForNotification(); return result; } VLOG(3) << "TryGetKeyValueRequest: " << request.DebugString(); &request, &response, [&](const absl::Status& s) { if (s.ok()) { result = response.kv().value(); VLOG(3) << "TryGetKeyValueResponse: " << result.value(); } else { result = s; VLOG(3) << "TryGetKeyValueResponse: " << s; } n.Notify(); }); VLOG(3) << "TryGetKeyValueResponse: " << result.value(); VLOG(3) << "TryGetKeyValueResponse: " << s; CoordinationServiceAgentImpl::GetKeyValueDir(std::string_view key) { absl::Notification n; absl::StatusOr<std::vector<KeyValueEntry>> result; GetKeyValueDirAsync( key, [&n, &result]( absl::StatusOr<std::vector<KeyValueEntry>> status_or_value) { result = std::move(status_or_value); n.Notify(); }); n.WaitForNotification(); return result; } key, [&n, &result]( absl::StatusOr<std::vector<KeyValueEntry>> status_or_value) { result = std::move(status_or_value); n.Notify(); }); void CoordinationServiceAgentImpl::GetKeyValueDirAsync( std::string_view key, StatusOrValueDirCallback done) { auto request = std::make_shared<GetKeyValueDirRequest>(); request->set_directory_key(key.data(), key.size()); VLOG(3) << "GetKeyValueDirRequest: " << request->DebugString(); auto response = std::make_shared<GetKeyValueDirResponse>(); leader_client_->GetKeyValueDirAsync( request.get(), response.get(), [request, response, done = std::move(done)](const absl::Status& s) { if (!s.ok()) { done(s); VLOG(3) << "GetKeyValueDirResponse: " << s; } else { VLOG(3) << "GetKeyValueDirResponse: " << response->DebugString(); std::vector<KeyValueEntry> kv_in_directory = { std::make_move_iterator(response->kv().begin()), std::make_move_iterator(response->kv().end())}; done(kv_in_directory); } }); } VLOG(3) << "GetKeyValueDirRequest: " << request->DebugString(); [request, response, done = std::move(done)](const absl::Status& s) { if (!s.ok()) { done(s); VLOG(3) << "GetKeyValueDirResponse: " << s; } else { VLOG(3) << "GetKeyValueDirResponse: " << response->DebugString(); std::vector<KeyValueEntry> kv_in_directory = { std::make_move_iterator(response->kv().begin()), std::make_move_iterator(response->kv().end())}; done(kv_in_directory); } }); VLOG(3) << "GetKeyValueDirResponse: " << s; VLOG(3) << "GetKeyValueDirResponse: " << response->DebugString(); absl::Status CoordinationServiceAgentImpl::InsertKeyValue( std::string_view key, std::string_view value) { return InsertKeyValue(key, value, /*allow_overwrite=*/false); } absl::Status CoordinationServiceAgentImpl::InsertKeyValue( std::string_view key, std::string_view value, bool allow_overwrite) { InsertKeyValueRequest request; request.mutable_kv()->set_key(key.data(), key.size()); request.mutable_kv()->set_value(value.data(), value.size()); request.set_allow_overwrite(allow_overwrite); VLOG(3) << "InsertKeyValueRequest: " << request.DebugString(); InsertKeyValueResponse response; absl::Status status; absl::Notification n; leader_client_->InsertKeyValueAsync(&request, &response, [&](absl::Status s) { status = s; n.Notify(); }); n.WaitForNotification(); VLOG(3) << "InsertKeyValueResponse: " << status; return status; } VLOG(3) << "InsertKeyValueRequest: " << request.DebugString(); leader_client_->InsertKeyValueAsync(&request, &response, [&](absl::Status s) { status = s; n.Notify(); }); VLOG(3) << "InsertKeyValueResponse: " << status; absl::Status CoordinationServiceAgentImpl::DeleteKeyValue( std::string_view key) { DeleteKeyValueRequest request; request.set_key(key.data(), key.size()); request.set_is_directory(true); VLOG(3) << "DeleteKeyValueRequest: " << request.DebugString(); DeleteKeyValueResponse response; absl::Status status; absl::Notification n; leader_client_->DeleteKeyValueAsync(&request, &response, [&](absl::Status s) { status = s; n.Notify(); }); n.WaitForNotification(); VLOG(3) << "DeleteKeyValueResponse " << status; return absl::OkStatus(); } VLOG(3) << "DeleteKeyValueRequest: " << request.DebugString(); leader_client_->DeleteKeyValueAsync(&request, &response, [&](absl::Status s) { status = s; n.Notify(); }); VLOG(3) << "DeleteKeyValueResponse " << status; absl::Status CoordinationServiceAgentImpl::UpdateKeyValue( std::string_view key, std::string_view value) { return MakeCoordinationError(absl::UnimplementedError( "CoordinationServiceAgent::UpdateKeyValue is not implemented.")); } absl::Status CoordinationServiceAgentImpl::StartWatchKey( std::string_view key, CoordinationServiceAgentImpl::ChangedKeyValuesCallback on_change) { return MakeCoordinationError(absl::UnimplementedError( "CoordinationServiceAgent::StartWatchKey is not implemented.")); } absl::Status CoordinationServiceAgentImpl::StopWatchKey(std::string_view key) { return MakeCoordinationError(absl::UnimplementedError( "CoordinationServiceAgent::StopWatchKey is not implemented.")); } void CoordinationServiceAgentImpl::SetError(const absl::Status& error) { assert(!error.ok()); absl::MutexLock l(&state_mu_); if (state_ == CoordinatedTaskState::TASKSTATE_ERROR) return; LOG(ERROR) << "Coordination agent is set to ERROR: " << error; state_ = CoordinatedTaskState::TASKSTATE_ERROR; status_ = error; error_fn_(error); } absl::Status CoordinationServiceAgentImpl::ActivateWatch( std::string_view key, const std::map<std::string, std::string>& kvs) { return MakeCoordinationError(absl::UnimplementedError( "CoordinationServiceAgent::ActivateWatch is not implemented.")); } absl::Status CoordinationServiceAgentImpl::WaitAtBarrier( std::string_view barrier_id, absl::Duration timeout, const std::vector<CoordinatedTask>& tasks) { absl::Status status; absl::Notification n; WaitAtBarrierAsync(barrier_id, timeout, tasks, [&](absl::Status s) { status = s; n.Notify(); }); n.WaitForNotification(); return status; } WaitAtBarrierAsync(barrier_id, timeout, tasks, [&](absl::Status s) { status = s; n.Notify(); }); void CoordinationServiceAgentImpl::WaitAtBarrierAsync( std::string_view barrier_id, absl::Duration timeout, const std::vector<CoordinatedTask>& tasks, StatusCallback done) { absl::Status agent_running_status = ValidateRunningAgent(/*allow_disconnected=*/true); if (!agent_running_status.ok()) { done(agent_running_status); return; } { absl::MutexLock l(&state_mu_); auto [it, inserted] = used_barrier_ids_.insert(std::string(barrier_id)); if (!inserted) { done(absl::FailedPreconditionError(absl::StrCat( "WaitAtBarrier() should not be called with the same id more than " "once. Barrier id: ", barrier_id))); return; } } auto request = std::make_shared<BarrierRequest>(); auto response = std::make_shared<BarrierResponse>(); request->set_barrier_id(std::string(barrier_id)); request->set_barrier_timeout_in_ms(timeout / absl::Milliseconds(1)); *request->mutable_source_task() = task_; *request->mutable_tasks() = {tasks.begin(), tasks.end()}; VLOG(3) << "WaitAtBarrierRequest: " << request->DebugString(); leader_client_->BarrierAsync( request.get(), response.get(), [request, response, done = std::move(done)](const absl::Status& s) { done(s); VLOG(3) << "WaitAtBarrierResponse: " << s; }); } VLOG(3) << "WaitAtBarrierRequest: " << request->DebugString(); [request, response, done = std::move(done)](const absl::Status& s) { done(s); VLOG(3) << "WaitAtBarrierResponse: " << s; }); VLOG(3) << "WaitAtBarrierResponse: " << s; absl::Status CoordinationServiceAgentImpl::CancelBarrier( std::string_view barrier_id) { absl::Status status; absl::Notification n; CancelBarrierAsync(barrier_id, [&](const absl::Status& s) { status = s; n.Notify(); }); n.WaitForNotification(); return status; } CancelBarrierAsync(barrier_id, [&](const absl::Status& s) { status = s; n.Notify(); }); void CoordinationServiceAgentImpl::CancelBarrierAsync( std::string_view barrier_id, StatusCallback done) { absl::Status agent_running_status = ValidateRunningAgent(/*allow_disconnected=*/true); if (!agent_running_status.ok()) { done(agent_running_status); return; } auto request = std::make_shared<CancelBarrierRequest>(); auto response = std::make_shared<CancelBarrierResponse>(); request->set_barrier_id(std::string(barrier_id)); *request->mutable_source_task() = task_; VLOG(3) << "CancelBarrierRequest: " << request->DebugString(); leader_client_->CancelBarrierAsync( request.get(), response.get(), [request, response, done = std::move(done)](const absl::Status& s) { done(s); VLOG(3) << "CancelBarrierResponse: " << s; }); } VLOG(3) << "CancelBarrierRequest: " << request->DebugString(); [request, response, done = std::move(done)](const absl::Status& s) { done(s); VLOG(3) << "CancelBarrierResponse: " << s; }); VLOG(3) << "CancelBarrierResponse: " << s; absl::Status CoordinationServiceAgentImpl::ValidateRunningAgent( bool allow_disconnected) { absl::MutexLock l(&state_mu_); switch (state_) { case CoordinatedTaskState::TASKSTATE_CONNECTED: return absl::OkStatus(); case CoordinatedTaskState::TASKSTATE_UNINITIALIZED: return MakeCoordinationError(absl::FailedPreconditionError( "Agent must be in CONNECTED state. It is currently UNINITIALIZED.")); case CoordinatedTaskState::TASKSTATE_DISCONNECTED: if (allow_disconnected) return absl::OkStatus(); return MakeCoordinationError(absl::FailedPreconditionError( "Agent must be in CONNECTED state. It is currently DISCONNECTED.")); case CoordinatedTaskState::TASKSTATE_ERROR: return MakeCoordinationError(absl::FailedPreconditionError( "Agent must be in CONNECTED state. It is currently in ERROR.")); default: return MakeCoordinationError(absl::FailedPreconditionError(absl::StrCat( "Agent is not in CONNECTED state. Current state: ", state_))); } } absl::StatusOr<Env*> CoordinationServiceAgentImpl::GetEnv() { if (!IsInitialized()) { return MakeCoordinationError(absl::FailedPreconditionError( "Coordination service agent has not been initialized.")); } if (env_ == nullptr) { return MakeCoordinationError( absl::FailedPreconditionError("Coordination service agent was not " "initialized with a valid Env* object.")); } return env_; } std::unique_ptr<CoordinationServiceAgent> CreateCoordinationServiceAgent() { return std::make_unique<CoordinationServiceAgentImpl>(); }
#include "xla/tsl/distributed_runtime/coordination/coordination_service_agent.h" #include <memory> #include <ostream> #include <string> #include <utility> #include <vector> #include "absl/log/check.h" #include "absl/log/log.h" #include "absl/memory/memory.h" #include "absl/status/status.h" #include "absl/time/clock.h" #include "absl/time/time.h" #include "xla/tsl/distributed_runtime/call_options.h" #include "xla/tsl/distributed_runtime/coordination/coordination_client.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/env.h" #include "tsl/platform/status.h" #include "tsl/platform/test.h" #include "tsl/protobuf/coordination_config.pb.h" #include "tsl/protobuf/coordination_service.pb.h" class CoordinationServiceAgentTest : public ::testing::Test { public: void SetUp() override { ON_CALL(*client_, RegisterTaskAsync(_, _, _, _)) .WillByDefault(InvokeArgument<3>(absl::OkStatus())); ON_CALL(*client_, HeartbeatAsync(_, _, _, _)) .WillByDefault(InvokeArgument<3>(absl::OkStatus())); ON_CALL(*client_, ShutdownTaskAsync(_, _, _, _)) .WillByDefault(InvokeArgument<3>(absl::OkStatus())); ON_CALL(*client_, ReportErrorToServiceAsync(_, _, _)) .WillByDefault(InvokeArgument<2>(absl::OkStatus())); ON_CALL(*client_, ResetTaskAsync(_, _, _)) .WillByDefault(InvokeArgument<2>(absl::OkStatus())); ON_CALL(*client_, BarrierAsync(_, _, _)) .WillByDefault(InvokeArgument<2>(absl::OkStatus())); ON_CALL(*client_, GetTaskStateAsync(_, _, _)) .WillByDefault(InvokeArgument<2>(absl::OkStatus())); } // Should be called after mocking service responses, before testing the agent. void InitializeAgent(CoordinationServiceConfig config = {}) { config.set_service_leader("test_leader"); TF_ASSERT_OK(agent_->Initialize( Env::Default(), /*job_name=*/"test_job", /*task_id=*/0, config, std::move(client_), /*error_fn=*/[](absl::Status s) { LOG(ERROR) << "Coordination agent is set to error: " << s; })); } TestCoordinationClient* GetClient() { // InitializeAgent() transfers ownership of the coordination client. CHECK(client_ != nullptr) << "GetClient() was called after InitializeAgent()"; return client_.get(); } protected: std::unique_ptr<CoordinationServiceAgent> agent_ = CreateCoordinationServiceAgent(); std::unique_ptr<TestCoordinationClient> client_ = std::make_unique<TestCoordinationClient>(); }; TEST_F(CoordinationServiceAgentTest, ShutdownInErrorShouldReturnError) { // Connect coordination agent and set it to error. InitializeAgent(); TF_ASSERT_OK(agent_->Connect()); TF_ASSERT_OK(agent_->ReportError(absl::InternalError("Test Error."))); // Shutdown should return error. absl::Status s = agent_->Shutdown(); EXPECT_TRUE(absl::IsFailedPrecondition(s)); }
HloBisectStateTest_TrimByInstructions
xla/tools/hlo_bisect/hlo_bisect_state_test.cc
std::vector<HloInstruction*> GetModifiedInstructionPostOrder( HloComputation* computation) { std::vector<HloInstruction*> instructions( computation->parameter_instructions().begin(), computation->parameter_instructions().end()); absl::c_copy_if(computation->MakeInstructionPostOrder(), std::back_inserter(instructions), [&](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kParameter; }); return instructions; } absl::Status MorphModuleWithOutputs(HloModule* module, absl::Span<HloInstruction* const> outputs) { HloComputation* entry_computation = module->entry_computation(); HloInstruction* new_root = outputs.size() == 1 ? outputs[0] : entry_computation->AddInstruction( HloInstruction::CreateTuple(outputs)); entry_computation->set_root_instruction(new_root, true); *module->mutable_entry_computation_layout() = module->compute_computation_layout(); HloDCE dce; absl::StatusOr<bool> dce_result = dce.Run(module); return dce_result.status(); } absl::Status MorphModuleWithInstructions( HloModule* module, absl::Span<HloInstruction* const> instructions) { ConstHloInstructionSet in_range_instructions(instructions.begin(), instructions.end()); auto keep_result = [&](const HloInstruction* instruction) { return instruction->opcode() != HloOpcode::kParameter && !absl::c_any_of(instruction->users(), [&](const HloInstruction* user) { return in_range_instructions.count(user) != 0; }); }; // If an instruction doesn't have a user within the range, add the result of // the instruction to the outputs to keep the value live. std::vector<HloInstruction*> outputs; absl::c_copy_if(instructions, std::back_inserter(outputs), keep_result); return MorphModuleWithOutputs(module, outputs); } auto keep_result = [&](const HloInstruction* instruction) { return instruction->opcode() != HloOpcode::kParameter && !absl::c_any_of(instruction->users(), [&](const HloInstruction* user) { return in_range_instructions.count(user) != 0; }); }; [&](const HloInstruction* user) { return in_range_instructions.count(user) != 0; }); absl::Status MorphModuleWithInstructions(HloModule* module, size_t num_instructions) { std::vector<HloInstruction*> ordered_instructions = GetModifiedInstructionPostOrder(module->entry_computation()); HloInstruction* const* instructions_begin = &ordered_instructions.front(); return MorphModuleWithInstructions( module, absl::MakeSpan(instructions_begin, num_instructions)); } absl::Status MorphModuleWithLiterals( HloModule* module, absl::flat_hash_map<std::string, Literal> literal_map) { HloComputation* entry_computation = module->entry_computation(); // Iterate over instructions, as lookup by instruction name is linear. absl::flat_hash_map<HloInstruction*, Literal> replace_map; for (HloInstruction* instruction : entry_computation->instructions()) { auto it = literal_map.find(instruction->name()); if (it != literal_map.end()) { replace_map.emplace(instruction, std::move(it->second)); } } for (auto& [instruction, literal] : replace_map) { if (!instruction->IsDead()) { HloInstruction* new_instruction = entry_computation->AddInstruction( HloInstruction::CreateConstant(std::move(literal))); absl::Status replace_status = entry_computation->ReplaceInstruction(instruction, new_instruction); TF_RETURN_IF_ERROR(replace_status); } } xla::HloDCE dce; absl::StatusOr<bool> dce_status = dce.Run(module); return dce_status.status(); } bool InstructionNotReplaceableWithConstant(HloInstruction* instruction) { return instruction->shape().is_dynamic() || instruction->opcode() == HloOpcode::kConstant || instruction->opcode() == HloOpcode::kTuple || instruction->opcode() == HloOpcode::kParameter; } absl::StatusOr<bool> HloBisectState::ShouldProcess() { // Running the unmodified module should trigger the bug checker. return RunModule(*module_); } absl::StatusOr<bool> HloBisectState::TrimEntryComputation() { bool changed_in_loop = false; bool changed = false; for (int iter = 0; changed || iter < 2; iter++) { if (iter % 2 == 0) { VLOG(2) << "Trimming by outputs, iteration " << iter; TF_ASSIGN_OR_RETURN(changed, TrimByOutputs()); } else { VLOG(2) << "Trimming by instructions, iteration " << iter; TF_ASSIGN_OR_RETURN(changed, TrimByInstructions()); } changed_in_loop |= changed; } VLOG(2) << "Trimming by replacing instructions with literals"; TF_ASSIGN_OR_RETURN(changed, TrimByUsingConstants()); VLOG(2) << "Final module: " << module_->ToString(); return changed || changed_in_loop; } VLOG(2) << "Trimming by outputs, iteration " << iter; VLOG(2) << "Trimming by instructions, iteration " << iter; VLOG(2) << "Trimming by replacing instructions with literals"; VLOG(2) << "Final module: " << module_->ToString(); std::unique_ptr<xla::HloModule>&& HloBisectState::GetResult() { return std::move(module_); } absl::StatusOr<bool> HloBisectState::RunModule(const HloModule& module) { VLOG(3) << "Modified module: " << module.ToString(); // Run the modified module with the bug checker. absl::StatusOr<bool> bug_result = bug_checker_->Run(module); TF_RETURN_IF_ERROR(bug_result.status()); VLOG(3) << "Bug checker result: " << bug_result.value(); // Update foldable instructions data. if (!bug_result.value()) { for (HloInstruction* instr : module.entry_computation()->instructions()) { foldable_instructions_.emplace(instr->name()); } for (auto& [key, value] : bug_checker_->GetResults()) { foldable_instructions_values_[key] = std::move(value); } } return bug_result; } VLOG(3) << "Modified module: " << module.ToString(); VLOG(3) << "Bug checker result: " << bug_result.value(); absl::StatusOr<bool> HloBisectState::TrimByOutputs() { // Only available if the root instruction is a tuple. HloInstruction* root_instruction = module_->entry_computation()->root_instruction(); if (root_instruction->opcode() != HloOpcode::kTuple || root_instruction->operand_count() < 2) { return false; } // Run the modified module and return the error state. auto run_modified = [&](int64_t start, int64_t end) -> absl::StatusOr<bool> { std::unique_ptr<HloModule> new_module = module_->Clone(/*suffix=*/""); HloInstruction* const* new_operands = new_module->entry_computation()->root_instruction()->operands().begin(); TF_RETURN_IF_ERROR(MorphModuleWithOutputs( new_module.get(), absl::MakeSpan(new_operands + start, end - start + 1))); return RunModule(*new_module); }; // Binary search for the operands range that exhibits a bug. int64_t bisect_low = 0; int64_t bisect_high = root_instruction->operand_count() - 1; while (bisect_low < bisect_high) { int64_t cur = bisect_low + (bisect_high - bisect_low) / 2; VLOG(2) << "Number of outputs: " << (cur - bisect_low + 1) << " [" << bisect_low << ".." << cur << "]"; TF_ASSIGN_OR_RETURN(bool has_bug, run_modified(bisect_low, cur)); if (has_bug) { bisect_high = cur; } else { TF_ASSIGN_OR_RETURN(has_bug, run_modified(cur + 1, bisect_high)); if (has_bug) { bisect_low = cur + 1; } else { break; } } } // Update the current module and verify that the bug is present, if changed. bool changed = (bisect_high - bisect_low) < (root_instruction->operand_count() - 1); if (changed) { TF_RETURN_IF_ERROR(MorphModuleWithOutputs( module_.get(), absl::MakeSpan(root_instruction->operands().begin() + bisect_low, bisect_high - bisect_low + 1))); TF_RETURN_IF_ERROR(ExpectModuleIsBuggy()); } return changed; } auto run_modified = [&](int64_t start, int64_t end) -> absl::StatusOr<bool> { std::unique_ptr<HloModule> new_module = module_->Clone(/*suffix=*/""); HloInstruction* const* new_operands = new_module->entry_computation()->root_instruction()->operands().begin(); TF_RETURN_IF_ERROR(MorphModuleWithOutputs( new_module.get(), absl::MakeSpan(new_operands + start, end - start + 1))); return RunModule(*new_module); }; VLOG(2) << "Number of outputs: " << (cur - bisect_low + 1) << " [" absl::StatusOr<bool> HloBisectState::TrimByInstructions() { HloComputation* computation = module_->entry_computation(); // If the root instruction is a tuple, exclude it from the bisect range. int64_t upper_bound = computation->instruction_count() - computation->root_instruction()->shape().IsTuple(); // Binary search for the instructions range that exhibits a bug. int64_t bisect_low = computation->num_parameters() - 1; int64_t bisect_high = upper_bound; while (bisect_low + 1 < bisect_high) { int64_t cur = bisect_low + (bisect_high - bisect_low) / 2; VLOG(2) << "Number of instructions: " << cur << " (of " << computation->instruction_count() << ")"; std::unique_ptr<HloModule> new_module = module_->Clone(/*suffix=*/""); TF_RETURN_IF_ERROR(MorphModuleWithInstructions(new_module.get(), cur)); TF_ASSIGN_OR_RETURN(bool has_bug, RunModule(*new_module)); if (has_bug) { bisect_high = cur; } else { bisect_low = cur; } } // Sanity check for the bug checker. if (bisect_high == computation->num_parameters()) { return Internal( "The checker fails on an empty computation! Something is not right. " "Can't bisect."); } // Update the current module and verify that the bug is present, if changed. bool changed = bisect_high < upper_bound; if (changed) { TF_RETURN_IF_ERROR(MorphModuleWithInstructions(module_.get(), bisect_high)); TF_RETURN_IF_ERROR(ExpectModuleIsBuggy()); } return changed; } VLOG(2) << "Number of instructions: " << cur << " (of " absl::StatusOr<bool> HloBisectState::TrimByUsingConstants() { // Use random literals for the instructions which do not trigger the bug // checker and also didn't get a definitive value from it. absl::flat_hash_map<std::string, Literal> literal_map; int64_t random_literals_count = 0; for (HloInstruction* instr : module_->entry_computation()->instructions()) { if (InstructionNotReplaceableWithConstant(instr)) { continue; } if (foldable_instructions_values_.contains(instr->name())) { auto it = foldable_instructions_values_.extract(instr->name()); literal_map.insert(std::move(it)); } else if (foldable_instructions_.contains(instr->name())) { absl::StatusOr<Literal> literal_status = MakeFakeLiteral(instr->shape()); TF_RETURN_IF_ERROR(literal_status.status()); literal_map[instr->name()] = std::move(literal_status).value(); ++random_literals_count; } } VLOG(2) << "Number of literals: " << literal_map.size() << " (random: " << random_literals_count << ")"; // Replace instructions with constants and run the bug checker. // It is possible that the random literals will make the bug disappear, in // which case the module will not get reduced. std::unique_ptr<HloModule> new_module = module_->Clone(/*suffix=*/""); TF_RETURN_IF_ERROR( MorphModuleWithLiterals(new_module.get(), std::move(literal_map))); TF_ASSIGN_OR_RETURN(bool has_bug, RunModule(*new_module)); if (has_bug) { std::swap(module_, new_module); } return has_bug; } VLOG(2) << "Number of literals: " << literal_map.size() absl::Status HloBisectState::ExpectModuleIsBuggy() { // Verify that the current module has a bug. TF_ASSIGN_OR_RETURN(bool has_bug, RunModule(*module_)); if (has_bug) { return absl::OkStatus(); } // Check for the bug checker stability. const int retry_count = 5; int bug_count = 0; for (int i = 0; i < retry_count; i++) { TF_ASSIGN_OR_RETURN(has_bug, bug_checker_->Run(*module_)); if (has_bug) { bug_count++; } } if (bug_count != 0) { return InternalStrCat("The checker is non deterministic! (only ", bug_count, " failures seen in ", (retry_count + 1), " runs)"); } return Internal("We \"lost\" the bug while bisecting!"); }
#include "xla/tools/hlo_bisect/hlo_bisect_state.h" #include <initializer_list> #include <string> #include <utility> #include <vector> #include "absl/algorithm/container.h" #include "absl/status/statusor.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/literal.h" #include "xla/service/pattern_matcher.h" #include "xla/service/pattern_matcher_gmock.h" #include "xla/tests/hlo_test_base.h" TEST_F(HloBisectStateTest, TrimByInstructions) { const char* kModuleStr = R"( HloModule axpy_module ENTRY axpy_computation { alpha = f32[] parameter(0) broadcast = f32[10] broadcast(alpha), dimensions={} x = f32[10] parameter(1) ax = f32[10] multiply(broadcast, x) y = f32[10] parameter(2) ROOT add = f32[10] add(ax, y) } )"; TF_ASSERT_OK_AND_ASSIGN(auto module, ParseAndReturnVerifiedModule(kModuleStr)); TestBugSearch bug_checker({HloOpcode::kMultiply, HloOpcode::kBroadcast}); HloBisectState bisect(std::move(module), &bug_checker); TF_ASSERT_OK_AND_ASSIGN(bool changed, bisect.TrimEntryComputation()); EXPECT_TRUE(changed); auto reduced_module = std::move(bisect).GetResult(); EXPECT_THAT( reduced_module->entry_computation()->root_instruction(), GmockMatch(m::Multiply(m::Broadcast(m::Parameter(0)), m::Parameter(1)))); }
HloBisectStateTest_TrimByOutputs
xla/tools/hlo_bisect/hlo_bisect_state_test.cc
std::vector<HloInstruction*> GetModifiedInstructionPostOrder( HloComputation* computation) { std::vector<HloInstruction*> instructions( computation->parameter_instructions().begin(), computation->parameter_instructions().end()); absl::c_copy_if(computation->MakeInstructionPostOrder(), std::back_inserter(instructions), [&](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kParameter; }); return instructions; } absl::Status MorphModuleWithOutputs(HloModule* module, absl::Span<HloInstruction* const> outputs) { HloComputation* entry_computation = module->entry_computation(); HloInstruction* new_root = outputs.size() == 1 ? outputs[0] : entry_computation->AddInstruction( HloInstruction::CreateTuple(outputs)); entry_computation->set_root_instruction(new_root, true); *module->mutable_entry_computation_layout() = module->compute_computation_layout(); HloDCE dce; absl::StatusOr<bool> dce_result = dce.Run(module); return dce_result.status(); } absl::Status MorphModuleWithInstructions( HloModule* module, absl::Span<HloInstruction* const> instructions) { ConstHloInstructionSet in_range_instructions(instructions.begin(), instructions.end()); auto keep_result = [&](const HloInstruction* instruction) { return instruction->opcode() != HloOpcode::kParameter && !absl::c_any_of(instruction->users(), [&](const HloInstruction* user) { return in_range_instructions.count(user) != 0; }); }; // If an instruction doesn't have a user within the range, add the result of // the instruction to the outputs to keep the value live. std::vector<HloInstruction*> outputs; absl::c_copy_if(instructions, std::back_inserter(outputs), keep_result); return MorphModuleWithOutputs(module, outputs); } auto keep_result = [&](const HloInstruction* instruction) { return instruction->opcode() != HloOpcode::kParameter && !absl::c_any_of(instruction->users(), [&](const HloInstruction* user) { return in_range_instructions.count(user) != 0; }); }; [&](const HloInstruction* user) { return in_range_instructions.count(user) != 0; }); absl::Status MorphModuleWithInstructions(HloModule* module, size_t num_instructions) { std::vector<HloInstruction*> ordered_instructions = GetModifiedInstructionPostOrder(module->entry_computation()); HloInstruction* const* instructions_begin = &ordered_instructions.front(); return MorphModuleWithInstructions( module, absl::MakeSpan(instructions_begin, num_instructions)); } absl::Status MorphModuleWithLiterals( HloModule* module, absl::flat_hash_map<std::string, Literal> literal_map) { HloComputation* entry_computation = module->entry_computation(); // Iterate over instructions, as lookup by instruction name is linear. absl::flat_hash_map<HloInstruction*, Literal> replace_map; for (HloInstruction* instruction : entry_computation->instructions()) { auto it = literal_map.find(instruction->name()); if (it != literal_map.end()) { replace_map.emplace(instruction, std::move(it->second)); } } for (auto& [instruction, literal] : replace_map) { if (!instruction->IsDead()) { HloInstruction* new_instruction = entry_computation->AddInstruction( HloInstruction::CreateConstant(std::move(literal))); absl::Status replace_status = entry_computation->ReplaceInstruction(instruction, new_instruction); TF_RETURN_IF_ERROR(replace_status); } } xla::HloDCE dce; absl::StatusOr<bool> dce_status = dce.Run(module); return dce_status.status(); } bool InstructionNotReplaceableWithConstant(HloInstruction* instruction) { return instruction->shape().is_dynamic() || instruction->opcode() == HloOpcode::kConstant || instruction->opcode() == HloOpcode::kTuple || instruction->opcode() == HloOpcode::kParameter; } absl::StatusOr<bool> HloBisectState::ShouldProcess() { // Running the unmodified module should trigger the bug checker. return RunModule(*module_); } absl::StatusOr<bool> HloBisectState::TrimEntryComputation() { bool changed_in_loop = false; bool changed = false; for (int iter = 0; changed || iter < 2; iter++) { if (iter % 2 == 0) { VLOG(2) << "Trimming by outputs, iteration " << iter; TF_ASSIGN_OR_RETURN(changed, TrimByOutputs()); } else { VLOG(2) << "Trimming by instructions, iteration " << iter; TF_ASSIGN_OR_RETURN(changed, TrimByInstructions()); } changed_in_loop |= changed; } VLOG(2) << "Trimming by replacing instructions with literals"; TF_ASSIGN_OR_RETURN(changed, TrimByUsingConstants()); VLOG(2) << "Final module: " << module_->ToString(); return changed || changed_in_loop; } VLOG(2) << "Trimming by outputs, iteration " << iter; VLOG(2) << "Trimming by instructions, iteration " << iter; VLOG(2) << "Trimming by replacing instructions with literals"; VLOG(2) << "Final module: " << module_->ToString(); std::unique_ptr<xla::HloModule>&& HloBisectState::GetResult() { return std::move(module_); } absl::StatusOr<bool> HloBisectState::RunModule(const HloModule& module) { VLOG(3) << "Modified module: " << module.ToString(); // Run the modified module with the bug checker. absl::StatusOr<bool> bug_result = bug_checker_->Run(module); TF_RETURN_IF_ERROR(bug_result.status()); VLOG(3) << "Bug checker result: " << bug_result.value(); // Update foldable instructions data. if (!bug_result.value()) { for (HloInstruction* instr : module.entry_computation()->instructions()) { foldable_instructions_.emplace(instr->name()); } for (auto& [key, value] : bug_checker_->GetResults()) { foldable_instructions_values_[key] = std::move(value); } } return bug_result; } VLOG(3) << "Modified module: " << module.ToString(); VLOG(3) << "Bug checker result: " << bug_result.value(); absl::StatusOr<bool> HloBisectState::TrimByOutputs() { // Only available if the root instruction is a tuple. HloInstruction* root_instruction = module_->entry_computation()->root_instruction(); if (root_instruction->opcode() != HloOpcode::kTuple || root_instruction->operand_count() < 2) { return false; } // Run the modified module and return the error state. auto run_modified = [&](int64_t start, int64_t end) -> absl::StatusOr<bool> { std::unique_ptr<HloModule> new_module = module_->Clone(/*suffix=*/""); HloInstruction* const* new_operands = new_module->entry_computation()->root_instruction()->operands().begin(); TF_RETURN_IF_ERROR(MorphModuleWithOutputs( new_module.get(), absl::MakeSpan(new_operands + start, end - start + 1))); return RunModule(*new_module); }; // Binary search for the operands range that exhibits a bug. int64_t bisect_low = 0; int64_t bisect_high = root_instruction->operand_count() - 1; while (bisect_low < bisect_high) { int64_t cur = bisect_low + (bisect_high - bisect_low) / 2; VLOG(2) << "Number of outputs: " << (cur - bisect_low + 1) << " [" << bisect_low << ".." << cur << "]"; TF_ASSIGN_OR_RETURN(bool has_bug, run_modified(bisect_low, cur)); if (has_bug) { bisect_high = cur; } else { TF_ASSIGN_OR_RETURN(has_bug, run_modified(cur + 1, bisect_high)); if (has_bug) { bisect_low = cur + 1; } else { break; } } } // Update the current module and verify that the bug is present, if changed. bool changed = (bisect_high - bisect_low) < (root_instruction->operand_count() - 1); if (changed) { TF_RETURN_IF_ERROR(MorphModuleWithOutputs( module_.get(), absl::MakeSpan(root_instruction->operands().begin() + bisect_low, bisect_high - bisect_low + 1))); TF_RETURN_IF_ERROR(ExpectModuleIsBuggy()); } return changed; } auto run_modified = [&](int64_t start, int64_t end) -> absl::StatusOr<bool> { std::unique_ptr<HloModule> new_module = module_->Clone(/*suffix=*/""); HloInstruction* const* new_operands = new_module->entry_computation()->root_instruction()->operands().begin(); TF_RETURN_IF_ERROR(MorphModuleWithOutputs( new_module.get(), absl::MakeSpan(new_operands + start, end - start + 1))); return RunModule(*new_module); }; VLOG(2) << "Number of outputs: " << (cur - bisect_low + 1) << " [" absl::StatusOr<bool> HloBisectState::TrimByInstructions() { HloComputation* computation = module_->entry_computation(); // If the root instruction is a tuple, exclude it from the bisect range. int64_t upper_bound = computation->instruction_count() - computation->root_instruction()->shape().IsTuple(); // Binary search for the instructions range that exhibits a bug. int64_t bisect_low = computation->num_parameters() - 1; int64_t bisect_high = upper_bound; while (bisect_low + 1 < bisect_high) { int64_t cur = bisect_low + (bisect_high - bisect_low) / 2; VLOG(2) << "Number of instructions: " << cur << " (of " << computation->instruction_count() << ")"; std::unique_ptr<HloModule> new_module = module_->Clone(/*suffix=*/""); TF_RETURN_IF_ERROR(MorphModuleWithInstructions(new_module.get(), cur)); TF_ASSIGN_OR_RETURN(bool has_bug, RunModule(*new_module)); if (has_bug) { bisect_high = cur; } else { bisect_low = cur; } } // Sanity check for the bug checker. if (bisect_high == computation->num_parameters()) { return Internal( "The checker fails on an empty computation! Something is not right. " "Can't bisect."); } // Update the current module and verify that the bug is present, if changed. bool changed = bisect_high < upper_bound; if (changed) { TF_RETURN_IF_ERROR(MorphModuleWithInstructions(module_.get(), bisect_high)); TF_RETURN_IF_ERROR(ExpectModuleIsBuggy()); } return changed; } VLOG(2) << "Number of instructions: " << cur << " (of " absl::StatusOr<bool> HloBisectState::TrimByUsingConstants() { // Use random literals for the instructions which do not trigger the bug // checker and also didn't get a definitive value from it. absl::flat_hash_map<std::string, Literal> literal_map; int64_t random_literals_count = 0; for (HloInstruction* instr : module_->entry_computation()->instructions()) { if (InstructionNotReplaceableWithConstant(instr)) { continue; } if (foldable_instructions_values_.contains(instr->name())) { auto it = foldable_instructions_values_.extract(instr->name()); literal_map.insert(std::move(it)); } else if (foldable_instructions_.contains(instr->name())) { absl::StatusOr<Literal> literal_status = MakeFakeLiteral(instr->shape()); TF_RETURN_IF_ERROR(literal_status.status()); literal_map[instr->name()] = std::move(literal_status).value(); ++random_literals_count; } } VLOG(2) << "Number of literals: " << literal_map.size() << " (random: " << random_literals_count << ")"; // Replace instructions with constants and run the bug checker. // It is possible that the random literals will make the bug disappear, in // which case the module will not get reduced. std::unique_ptr<HloModule> new_module = module_->Clone(/*suffix=*/""); TF_RETURN_IF_ERROR( MorphModuleWithLiterals(new_module.get(), std::move(literal_map))); TF_ASSIGN_OR_RETURN(bool has_bug, RunModule(*new_module)); if (has_bug) { std::swap(module_, new_module); } return has_bug; } VLOG(2) << "Number of literals: " << literal_map.size() absl::Status HloBisectState::ExpectModuleIsBuggy() { // Verify that the current module has a bug. TF_ASSIGN_OR_RETURN(bool has_bug, RunModule(*module_)); if (has_bug) { return absl::OkStatus(); } // Check for the bug checker stability. const int retry_count = 5; int bug_count = 0; for (int i = 0; i < retry_count; i++) { TF_ASSIGN_OR_RETURN(has_bug, bug_checker_->Run(*module_)); if (has_bug) { bug_count++; } } if (bug_count != 0) { return InternalStrCat("The checker is non deterministic! (only ", bug_count, " failures seen in ", (retry_count + 1), " runs)"); } return Internal("We \"lost\" the bug while bisecting!"); }
#include "xla/tools/hlo_bisect/hlo_bisect_state.h" #include <initializer_list> #include <string> #include <utility> #include <vector> #include "absl/algorithm/container.h" #include "absl/status/statusor.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/literal.h" #include "xla/service/pattern_matcher.h" #include "xla/service/pattern_matcher_gmock.h" #include "xla/tests/hlo_test_base.h" TEST_F(HloBisectStateTest, TrimByOutputs) { const char* kModuleStr = R"( HloModule test_module ENTRY test_computation { p1 = s32[8] parameter(0) p2 = s32[8] parameter(1) a = s32[8] add(p1, p2) b = s32[8] multiply(p1, p2) c = s32[8] subtract(p1, p2) ROOT sum = tuple(a, b, c) } )"; TF_ASSERT_OK_AND_ASSIGN(auto module, ParseAndReturnVerifiedModule(kModuleStr)); TestBugSearch bug_checker({HloOpcode::kMultiply}); HloBisectState bisect(std::move(module), &bug_checker); TF_ASSERT_OK_AND_ASSIGN(bool changed, bisect.TrimEntryComputation()); EXPECT_TRUE(changed); auto reduced_module = std::move(bisect).GetResult(); EXPECT_THAT(reduced_module->entry_computation()->root_instruction(), GmockMatch(m::Multiply(m::Parameter(0), m::Parameter(1)))); }
HloBisectStateTest_TrimByOutputsLostBug
xla/tools/hlo_bisect/hlo_bisect_state_test.cc
std::vector<HloInstruction*> GetModifiedInstructionPostOrder( HloComputation* computation) { std::vector<HloInstruction*> instructions( computation->parameter_instructions().begin(), computation->parameter_instructions().end()); absl::c_copy_if(computation->MakeInstructionPostOrder(), std::back_inserter(instructions), [&](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kParameter; }); return instructions; } absl::Status MorphModuleWithOutputs(HloModule* module, absl::Span<HloInstruction* const> outputs) { HloComputation* entry_computation = module->entry_computation(); HloInstruction* new_root = outputs.size() == 1 ? outputs[0] : entry_computation->AddInstruction( HloInstruction::CreateTuple(outputs)); entry_computation->set_root_instruction(new_root, true); *module->mutable_entry_computation_layout() = module->compute_computation_layout(); HloDCE dce; absl::StatusOr<bool> dce_result = dce.Run(module); return dce_result.status(); } absl::Status MorphModuleWithInstructions( HloModule* module, absl::Span<HloInstruction* const> instructions) { ConstHloInstructionSet in_range_instructions(instructions.begin(), instructions.end()); auto keep_result = [&](const HloInstruction* instruction) { return instruction->opcode() != HloOpcode::kParameter && !absl::c_any_of(instruction->users(), [&](const HloInstruction* user) { return in_range_instructions.count(user) != 0; }); }; // If an instruction doesn't have a user within the range, add the result of // the instruction to the outputs to keep the value live. std::vector<HloInstruction*> outputs; absl::c_copy_if(instructions, std::back_inserter(outputs), keep_result); return MorphModuleWithOutputs(module, outputs); } auto keep_result = [&](const HloInstruction* instruction) { return instruction->opcode() != HloOpcode::kParameter && !absl::c_any_of(instruction->users(), [&](const HloInstruction* user) { return in_range_instructions.count(user) != 0; }); }; [&](const HloInstruction* user) { return in_range_instructions.count(user) != 0; }); absl::Status MorphModuleWithInstructions(HloModule* module, size_t num_instructions) { std::vector<HloInstruction*> ordered_instructions = GetModifiedInstructionPostOrder(module->entry_computation()); HloInstruction* const* instructions_begin = &ordered_instructions.front(); return MorphModuleWithInstructions( module, absl::MakeSpan(instructions_begin, num_instructions)); } absl::Status MorphModuleWithLiterals( HloModule* module, absl::flat_hash_map<std::string, Literal> literal_map) { HloComputation* entry_computation = module->entry_computation(); // Iterate over instructions, as lookup by instruction name is linear. absl::flat_hash_map<HloInstruction*, Literal> replace_map; for (HloInstruction* instruction : entry_computation->instructions()) { auto it = literal_map.find(instruction->name()); if (it != literal_map.end()) { replace_map.emplace(instruction, std::move(it->second)); } } for (auto& [instruction, literal] : replace_map) { if (!instruction->IsDead()) { HloInstruction* new_instruction = entry_computation->AddInstruction( HloInstruction::CreateConstant(std::move(literal))); absl::Status replace_status = entry_computation->ReplaceInstruction(instruction, new_instruction); TF_RETURN_IF_ERROR(replace_status); } } xla::HloDCE dce; absl::StatusOr<bool> dce_status = dce.Run(module); return dce_status.status(); } bool InstructionNotReplaceableWithConstant(HloInstruction* instruction) { return instruction->shape().is_dynamic() || instruction->opcode() == HloOpcode::kConstant || instruction->opcode() == HloOpcode::kTuple || instruction->opcode() == HloOpcode::kParameter; } absl::StatusOr<bool> HloBisectState::ShouldProcess() { // Running the unmodified module should trigger the bug checker. return RunModule(*module_); } absl::StatusOr<bool> HloBisectState::TrimEntryComputation() { bool changed_in_loop = false; bool changed = false; for (int iter = 0; changed || iter < 2; iter++) { if (iter % 2 == 0) { VLOG(2) << "Trimming by outputs, iteration " << iter; TF_ASSIGN_OR_RETURN(changed, TrimByOutputs()); } else { VLOG(2) << "Trimming by instructions, iteration " << iter; TF_ASSIGN_OR_RETURN(changed, TrimByInstructions()); } changed_in_loop |= changed; } VLOG(2) << "Trimming by replacing instructions with literals"; TF_ASSIGN_OR_RETURN(changed, TrimByUsingConstants()); VLOG(2) << "Final module: " << module_->ToString(); return changed || changed_in_loop; } VLOG(2) << "Trimming by outputs, iteration " << iter; VLOG(2) << "Trimming by instructions, iteration " << iter; VLOG(2) << "Trimming by replacing instructions with literals"; VLOG(2) << "Final module: " << module_->ToString(); std::unique_ptr<xla::HloModule>&& HloBisectState::GetResult() { return std::move(module_); } absl::StatusOr<bool> HloBisectState::RunModule(const HloModule& module) { VLOG(3) << "Modified module: " << module.ToString(); // Run the modified module with the bug checker. absl::StatusOr<bool> bug_result = bug_checker_->Run(module); TF_RETURN_IF_ERROR(bug_result.status()); VLOG(3) << "Bug checker result: " << bug_result.value(); // Update foldable instructions data. if (!bug_result.value()) { for (HloInstruction* instr : module.entry_computation()->instructions()) { foldable_instructions_.emplace(instr->name()); } for (auto& [key, value] : bug_checker_->GetResults()) { foldable_instructions_values_[key] = std::move(value); } } return bug_result; } VLOG(3) << "Modified module: " << module.ToString(); VLOG(3) << "Bug checker result: " << bug_result.value(); absl::StatusOr<bool> HloBisectState::TrimByOutputs() { // Only available if the root instruction is a tuple. HloInstruction* root_instruction = module_->entry_computation()->root_instruction(); if (root_instruction->opcode() != HloOpcode::kTuple || root_instruction->operand_count() < 2) { return false; } // Run the modified module and return the error state. auto run_modified = [&](int64_t start, int64_t end) -> absl::StatusOr<bool> { std::unique_ptr<HloModule> new_module = module_->Clone(/*suffix=*/""); HloInstruction* const* new_operands = new_module->entry_computation()->root_instruction()->operands().begin(); TF_RETURN_IF_ERROR(MorphModuleWithOutputs( new_module.get(), absl::MakeSpan(new_operands + start, end - start + 1))); return RunModule(*new_module); }; // Binary search for the operands range that exhibits a bug. int64_t bisect_low = 0; int64_t bisect_high = root_instruction->operand_count() - 1; while (bisect_low < bisect_high) { int64_t cur = bisect_low + (bisect_high - bisect_low) / 2; VLOG(2) << "Number of outputs: " << (cur - bisect_low + 1) << " [" << bisect_low << ".." << cur << "]"; TF_ASSIGN_OR_RETURN(bool has_bug, run_modified(bisect_low, cur)); if (has_bug) { bisect_high = cur; } else { TF_ASSIGN_OR_RETURN(has_bug, run_modified(cur + 1, bisect_high)); if (has_bug) { bisect_low = cur + 1; } else { break; } } } // Update the current module and verify that the bug is present, if changed. bool changed = (bisect_high - bisect_low) < (root_instruction->operand_count() - 1); if (changed) { TF_RETURN_IF_ERROR(MorphModuleWithOutputs( module_.get(), absl::MakeSpan(root_instruction->operands().begin() + bisect_low, bisect_high - bisect_low + 1))); TF_RETURN_IF_ERROR(ExpectModuleIsBuggy()); } return changed; } auto run_modified = [&](int64_t start, int64_t end) -> absl::StatusOr<bool> { std::unique_ptr<HloModule> new_module = module_->Clone(/*suffix=*/""); HloInstruction* const* new_operands = new_module->entry_computation()->root_instruction()->operands().begin(); TF_RETURN_IF_ERROR(MorphModuleWithOutputs( new_module.get(), absl::MakeSpan(new_operands + start, end - start + 1))); return RunModule(*new_module); }; VLOG(2) << "Number of outputs: " << (cur - bisect_low + 1) << " [" absl::StatusOr<bool> HloBisectState::TrimByInstructions() { HloComputation* computation = module_->entry_computation(); // If the root instruction is a tuple, exclude it from the bisect range. int64_t upper_bound = computation->instruction_count() - computation->root_instruction()->shape().IsTuple(); // Binary search for the instructions range that exhibits a bug. int64_t bisect_low = computation->num_parameters() - 1; int64_t bisect_high = upper_bound; while (bisect_low + 1 < bisect_high) { int64_t cur = bisect_low + (bisect_high - bisect_low) / 2; VLOG(2) << "Number of instructions: " << cur << " (of " << computation->instruction_count() << ")"; std::unique_ptr<HloModule> new_module = module_->Clone(/*suffix=*/""); TF_RETURN_IF_ERROR(MorphModuleWithInstructions(new_module.get(), cur)); TF_ASSIGN_OR_RETURN(bool has_bug, RunModule(*new_module)); if (has_bug) { bisect_high = cur; } else { bisect_low = cur; } } // Sanity check for the bug checker. if (bisect_high == computation->num_parameters()) { return Internal( "The checker fails on an empty computation! Something is not right. " "Can't bisect."); } // Update the current module and verify that the bug is present, if changed. bool changed = bisect_high < upper_bound; if (changed) { TF_RETURN_IF_ERROR(MorphModuleWithInstructions(module_.get(), bisect_high)); TF_RETURN_IF_ERROR(ExpectModuleIsBuggy()); } return changed; } VLOG(2) << "Number of instructions: " << cur << " (of " absl::StatusOr<bool> HloBisectState::TrimByUsingConstants() { // Use random literals for the instructions which do not trigger the bug // checker and also didn't get a definitive value from it. absl::flat_hash_map<std::string, Literal> literal_map; int64_t random_literals_count = 0; for (HloInstruction* instr : module_->entry_computation()->instructions()) { if (InstructionNotReplaceableWithConstant(instr)) { continue; } if (foldable_instructions_values_.contains(instr->name())) { auto it = foldable_instructions_values_.extract(instr->name()); literal_map.insert(std::move(it)); } else if (foldable_instructions_.contains(instr->name())) { absl::StatusOr<Literal> literal_status = MakeFakeLiteral(instr->shape()); TF_RETURN_IF_ERROR(literal_status.status()); literal_map[instr->name()] = std::move(literal_status).value(); ++random_literals_count; } } VLOG(2) << "Number of literals: " << literal_map.size() << " (random: " << random_literals_count << ")"; // Replace instructions with constants and run the bug checker. // It is possible that the random literals will make the bug disappear, in // which case the module will not get reduced. std::unique_ptr<HloModule> new_module = module_->Clone(/*suffix=*/""); TF_RETURN_IF_ERROR( MorphModuleWithLiterals(new_module.get(), std::move(literal_map))); TF_ASSIGN_OR_RETURN(bool has_bug, RunModule(*new_module)); if (has_bug) { std::swap(module_, new_module); } return has_bug; } VLOG(2) << "Number of literals: " << literal_map.size() absl::Status HloBisectState::ExpectModuleIsBuggy() { // Verify that the current module has a bug. TF_ASSIGN_OR_RETURN(bool has_bug, RunModule(*module_)); if (has_bug) { return absl::OkStatus(); } // Check for the bug checker stability. const int retry_count = 5; int bug_count = 0; for (int i = 0; i < retry_count; i++) { TF_ASSIGN_OR_RETURN(has_bug, bug_checker_->Run(*module_)); if (has_bug) { bug_count++; } } if (bug_count != 0) { return InternalStrCat("The checker is non deterministic! (only ", bug_count, " failures seen in ", (retry_count + 1), " runs)"); } return Internal("We \"lost\" the bug while bisecting!"); }
#include "xla/tools/hlo_bisect/hlo_bisect_state.h" #include <initializer_list> #include <string> #include <utility> #include <vector> #include "absl/algorithm/container.h" #include "absl/status/statusor.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/literal.h" #include "xla/service/pattern_matcher.h" #include "xla/service/pattern_matcher_gmock.h" #include "xla/tests/hlo_test_base.h" TEST_F(HloBisectStateTest, TrimByOutputsLostBug) { class CustomBugSearch : public TestBugSearch { public: CustomBugSearch() : TestBugSearch({HloOpcode::kConstant}) {} absl::StatusOr<bool> Run(const HloModule& module) override { TF_ASSIGN_OR_RETURN(bool has_constants, TestBugSearch::Run(module)); int program_size = module.entry_computation()->instruction_count(); return program_size == 5 && !has_constants; } }; const char* kModuleStr = R"( HloModule test_module ENTRY test_computation { p1 = s32[8] parameter(0) p2 = s32[8] parameter(1) a = s32[8] add(p1, p2) b = s32[8] multiply(p1, p2) ROOT sum = tuple(a, b) } )"; TF_ASSERT_OK_AND_ASSIGN(auto module, ParseAndReturnVerifiedModule(kModuleStr)); CustomBugSearch bug_checker; HloBisectState bisect(std::move(module), &bug_checker); TF_ASSERT_OK_AND_ASSIGN(bool changed, bisect.TrimEntryComputation()); EXPECT_FALSE(changed); }
HloBisectStateTest_TrimByUsingRandomConstants
xla/tools/hlo_bisect/hlo_bisect_state_test.cc
std::vector<HloInstruction*> GetModifiedInstructionPostOrder( HloComputation* computation) { std::vector<HloInstruction*> instructions( computation->parameter_instructions().begin(), computation->parameter_instructions().end()); absl::c_copy_if(computation->MakeInstructionPostOrder(), std::back_inserter(instructions), [&](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kParameter; }); return instructions; } absl::Status MorphModuleWithOutputs(HloModule* module, absl::Span<HloInstruction* const> outputs) { HloComputation* entry_computation = module->entry_computation(); HloInstruction* new_root = outputs.size() == 1 ? outputs[0] : entry_computation->AddInstruction( HloInstruction::CreateTuple(outputs)); entry_computation->set_root_instruction(new_root, true); *module->mutable_entry_computation_layout() = module->compute_computation_layout(); HloDCE dce; absl::StatusOr<bool> dce_result = dce.Run(module); return dce_result.status(); } absl::Status MorphModuleWithInstructions( HloModule* module, absl::Span<HloInstruction* const> instructions) { ConstHloInstructionSet in_range_instructions(instructions.begin(), instructions.end()); auto keep_result = [&](const HloInstruction* instruction) { return instruction->opcode() != HloOpcode::kParameter && !absl::c_any_of(instruction->users(), [&](const HloInstruction* user) { return in_range_instructions.count(user) != 0; }); }; // If an instruction doesn't have a user within the range, add the result of // the instruction to the outputs to keep the value live. std::vector<HloInstruction*> outputs; absl::c_copy_if(instructions, std::back_inserter(outputs), keep_result); return MorphModuleWithOutputs(module, outputs); } auto keep_result = [&](const HloInstruction* instruction) { return instruction->opcode() != HloOpcode::kParameter && !absl::c_any_of(instruction->users(), [&](const HloInstruction* user) { return in_range_instructions.count(user) != 0; }); }; [&](const HloInstruction* user) { return in_range_instructions.count(user) != 0; }); absl::Status MorphModuleWithInstructions(HloModule* module, size_t num_instructions) { std::vector<HloInstruction*> ordered_instructions = GetModifiedInstructionPostOrder(module->entry_computation()); HloInstruction* const* instructions_begin = &ordered_instructions.front(); return MorphModuleWithInstructions( module, absl::MakeSpan(instructions_begin, num_instructions)); } absl::Status MorphModuleWithLiterals( HloModule* module, absl::flat_hash_map<std::string, Literal> literal_map) { HloComputation* entry_computation = module->entry_computation(); // Iterate over instructions, as lookup by instruction name is linear. absl::flat_hash_map<HloInstruction*, Literal> replace_map; for (HloInstruction* instruction : entry_computation->instructions()) { auto it = literal_map.find(instruction->name()); if (it != literal_map.end()) { replace_map.emplace(instruction, std::move(it->second)); } } for (auto& [instruction, literal] : replace_map) { if (!instruction->IsDead()) { HloInstruction* new_instruction = entry_computation->AddInstruction( HloInstruction::CreateConstant(std::move(literal))); absl::Status replace_status = entry_computation->ReplaceInstruction(instruction, new_instruction); TF_RETURN_IF_ERROR(replace_status); } } xla::HloDCE dce; absl::StatusOr<bool> dce_status = dce.Run(module); return dce_status.status(); } bool InstructionNotReplaceableWithConstant(HloInstruction* instruction) { return instruction->shape().is_dynamic() || instruction->opcode() == HloOpcode::kConstant || instruction->opcode() == HloOpcode::kTuple || instruction->opcode() == HloOpcode::kParameter; } absl::StatusOr<bool> HloBisectState::ShouldProcess() { // Running the unmodified module should trigger the bug checker. return RunModule(*module_); } absl::StatusOr<bool> HloBisectState::TrimEntryComputation() { bool changed_in_loop = false; bool changed = false; for (int iter = 0; changed || iter < 2; iter++) { if (iter % 2 == 0) { VLOG(2) << "Trimming by outputs, iteration " << iter; TF_ASSIGN_OR_RETURN(changed, TrimByOutputs()); } else { VLOG(2) << "Trimming by instructions, iteration " << iter; TF_ASSIGN_OR_RETURN(changed, TrimByInstructions()); } changed_in_loop |= changed; } VLOG(2) << "Trimming by replacing instructions with literals"; TF_ASSIGN_OR_RETURN(changed, TrimByUsingConstants()); VLOG(2) << "Final module: " << module_->ToString(); return changed || changed_in_loop; } VLOG(2) << "Trimming by outputs, iteration " << iter; VLOG(2) << "Trimming by instructions, iteration " << iter; VLOG(2) << "Trimming by replacing instructions with literals"; VLOG(2) << "Final module: " << module_->ToString(); std::unique_ptr<xla::HloModule>&& HloBisectState::GetResult() { return std::move(module_); } absl::StatusOr<bool> HloBisectState::RunModule(const HloModule& module) { VLOG(3) << "Modified module: " << module.ToString(); // Run the modified module with the bug checker. absl::StatusOr<bool> bug_result = bug_checker_->Run(module); TF_RETURN_IF_ERROR(bug_result.status()); VLOG(3) << "Bug checker result: " << bug_result.value(); // Update foldable instructions data. if (!bug_result.value()) { for (HloInstruction* instr : module.entry_computation()->instructions()) { foldable_instructions_.emplace(instr->name()); } for (auto& [key, value] : bug_checker_->GetResults()) { foldable_instructions_values_[key] = std::move(value); } } return bug_result; } VLOG(3) << "Modified module: " << module.ToString(); VLOG(3) << "Bug checker result: " << bug_result.value(); absl::StatusOr<bool> HloBisectState::TrimByOutputs() { // Only available if the root instruction is a tuple. HloInstruction* root_instruction = module_->entry_computation()->root_instruction(); if (root_instruction->opcode() != HloOpcode::kTuple || root_instruction->operand_count() < 2) { return false; } // Run the modified module and return the error state. auto run_modified = [&](int64_t start, int64_t end) -> absl::StatusOr<bool> { std::unique_ptr<HloModule> new_module = module_->Clone(/*suffix=*/""); HloInstruction* const* new_operands = new_module->entry_computation()->root_instruction()->operands().begin(); TF_RETURN_IF_ERROR(MorphModuleWithOutputs( new_module.get(), absl::MakeSpan(new_operands + start, end - start + 1))); return RunModule(*new_module); }; // Binary search for the operands range that exhibits a bug. int64_t bisect_low = 0; int64_t bisect_high = root_instruction->operand_count() - 1; while (bisect_low < bisect_high) { int64_t cur = bisect_low + (bisect_high - bisect_low) / 2; VLOG(2) << "Number of outputs: " << (cur - bisect_low + 1) << " [" << bisect_low << ".." << cur << "]"; TF_ASSIGN_OR_RETURN(bool has_bug, run_modified(bisect_low, cur)); if (has_bug) { bisect_high = cur; } else { TF_ASSIGN_OR_RETURN(has_bug, run_modified(cur + 1, bisect_high)); if (has_bug) { bisect_low = cur + 1; } else { break; } } } // Update the current module and verify that the bug is present, if changed. bool changed = (bisect_high - bisect_low) < (root_instruction->operand_count() - 1); if (changed) { TF_RETURN_IF_ERROR(MorphModuleWithOutputs( module_.get(), absl::MakeSpan(root_instruction->operands().begin() + bisect_low, bisect_high - bisect_low + 1))); TF_RETURN_IF_ERROR(ExpectModuleIsBuggy()); } return changed; } auto run_modified = [&](int64_t start, int64_t end) -> absl::StatusOr<bool> { std::unique_ptr<HloModule> new_module = module_->Clone(/*suffix=*/""); HloInstruction* const* new_operands = new_module->entry_computation()->root_instruction()->operands().begin(); TF_RETURN_IF_ERROR(MorphModuleWithOutputs( new_module.get(), absl::MakeSpan(new_operands + start, end - start + 1))); return RunModule(*new_module); }; VLOG(2) << "Number of outputs: " << (cur - bisect_low + 1) << " [" absl::StatusOr<bool> HloBisectState::TrimByInstructions() { HloComputation* computation = module_->entry_computation(); // If the root instruction is a tuple, exclude it from the bisect range. int64_t upper_bound = computation->instruction_count() - computation->root_instruction()->shape().IsTuple(); // Binary search for the instructions range that exhibits a bug. int64_t bisect_low = computation->num_parameters() - 1; int64_t bisect_high = upper_bound; while (bisect_low + 1 < bisect_high) { int64_t cur = bisect_low + (bisect_high - bisect_low) / 2; VLOG(2) << "Number of instructions: " << cur << " (of " << computation->instruction_count() << ")"; std::unique_ptr<HloModule> new_module = module_->Clone(/*suffix=*/""); TF_RETURN_IF_ERROR(MorphModuleWithInstructions(new_module.get(), cur)); TF_ASSIGN_OR_RETURN(bool has_bug, RunModule(*new_module)); if (has_bug) { bisect_high = cur; } else { bisect_low = cur; } } // Sanity check for the bug checker. if (bisect_high == computation->num_parameters()) { return Internal( "The checker fails on an empty computation! Something is not right. " "Can't bisect."); } // Update the current module and verify that the bug is present, if changed. bool changed = bisect_high < upper_bound; if (changed) { TF_RETURN_IF_ERROR(MorphModuleWithInstructions(module_.get(), bisect_high)); TF_RETURN_IF_ERROR(ExpectModuleIsBuggy()); } return changed; } VLOG(2) << "Number of instructions: " << cur << " (of " absl::StatusOr<bool> HloBisectState::TrimByUsingConstants() { // Use random literals for the instructions which do not trigger the bug // checker and also didn't get a definitive value from it. absl::flat_hash_map<std::string, Literal> literal_map; int64_t random_literals_count = 0; for (HloInstruction* instr : module_->entry_computation()->instructions()) { if (InstructionNotReplaceableWithConstant(instr)) { continue; } if (foldable_instructions_values_.contains(instr->name())) { auto it = foldable_instructions_values_.extract(instr->name()); literal_map.insert(std::move(it)); } else if (foldable_instructions_.contains(instr->name())) { absl::StatusOr<Literal> literal_status = MakeFakeLiteral(instr->shape()); TF_RETURN_IF_ERROR(literal_status.status()); literal_map[instr->name()] = std::move(literal_status).value(); ++random_literals_count; } } VLOG(2) << "Number of literals: " << literal_map.size() << " (random: " << random_literals_count << ")"; // Replace instructions with constants and run the bug checker. // It is possible that the random literals will make the bug disappear, in // which case the module will not get reduced. std::unique_ptr<HloModule> new_module = module_->Clone(/*suffix=*/""); TF_RETURN_IF_ERROR( MorphModuleWithLiterals(new_module.get(), std::move(literal_map))); TF_ASSIGN_OR_RETURN(bool has_bug, RunModule(*new_module)); if (has_bug) { std::swap(module_, new_module); } return has_bug; } VLOG(2) << "Number of literals: " << literal_map.size() absl::Status HloBisectState::ExpectModuleIsBuggy() { // Verify that the current module has a bug. TF_ASSIGN_OR_RETURN(bool has_bug, RunModule(*module_)); if (has_bug) { return absl::OkStatus(); } // Check for the bug checker stability. const int retry_count = 5; int bug_count = 0; for (int i = 0; i < retry_count; i++) { TF_ASSIGN_OR_RETURN(has_bug, bug_checker_->Run(*module_)); if (has_bug) { bug_count++; } } if (bug_count != 0) { return InternalStrCat("The checker is non deterministic! (only ", bug_count, " failures seen in ", (retry_count + 1), " runs)"); } return Internal("We \"lost\" the bug while bisecting!"); }
#include "xla/tools/hlo_bisect/hlo_bisect_state.h" #include <initializer_list> #include <string> #include <utility> #include <vector> #include "absl/algorithm/container.h" #include "absl/status/statusor.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/literal.h" #include "xla/service/pattern_matcher.h" #include "xla/service/pattern_matcher_gmock.h" #include "xla/tests/hlo_test_base.h" TEST_F(HloBisectStateTest, TrimByUsingRandomConstants) { const char* kModuleStr = R"( HloModule test_module ENTRY test_computation { p1 = f32[4] parameter(0) p2 = f32[4] parameter(1) a = f32[4] multiply(p1, p2) b = f32[4] add(p1, p2) ROOT result = f32[4] power(a, b) } )"; TF_ASSERT_OK_AND_ASSIGN(auto module, ParseAndReturnVerifiedModule(kModuleStr)); TestBugSearch bug_checker({HloOpcode::kPower}); HloBisectState bisect(std::move(module), &bug_checker); TF_ASSERT_OK_AND_ASSIGN(bool changed, bisect.TrimEntryComputation()); EXPECT_TRUE(changed); auto reduced_module = std::move(bisect).GetResult(); EXPECT_THAT(reduced_module->entry_computation()->root_instruction(), GmockMatch(m::Power(m::Constant(), m::Constant()))); }
HloBisectStateTest_TrimByUsingReferenceConstants
xla/tools/hlo_bisect/hlo_bisect_state_test.cc
std::vector<HloInstruction*> GetModifiedInstructionPostOrder( HloComputation* computation) { std::vector<HloInstruction*> instructions( computation->parameter_instructions().begin(), computation->parameter_instructions().end()); absl::c_copy_if(computation->MakeInstructionPostOrder(), std::back_inserter(instructions), [&](const HloInstruction* instr) { return instr->opcode() != HloOpcode::kParameter; }); return instructions; } absl::Status MorphModuleWithOutputs(HloModule* module, absl::Span<HloInstruction* const> outputs) { HloComputation* entry_computation = module->entry_computation(); HloInstruction* new_root = outputs.size() == 1 ? outputs[0] : entry_computation->AddInstruction( HloInstruction::CreateTuple(outputs)); entry_computation->set_root_instruction(new_root, true); *module->mutable_entry_computation_layout() = module->compute_computation_layout(); HloDCE dce; absl::StatusOr<bool> dce_result = dce.Run(module); return dce_result.status(); } absl::Status MorphModuleWithInstructions( HloModule* module, absl::Span<HloInstruction* const> instructions) { ConstHloInstructionSet in_range_instructions(instructions.begin(), instructions.end()); auto keep_result = [&](const HloInstruction* instruction) { return instruction->opcode() != HloOpcode::kParameter && !absl::c_any_of(instruction->users(), [&](const HloInstruction* user) { return in_range_instructions.count(user) != 0; }); }; // If an instruction doesn't have a user within the range, add the result of // the instruction to the outputs to keep the value live. std::vector<HloInstruction*> outputs; absl::c_copy_if(instructions, std::back_inserter(outputs), keep_result); return MorphModuleWithOutputs(module, outputs); } auto keep_result = [&](const HloInstruction* instruction) { return instruction->opcode() != HloOpcode::kParameter && !absl::c_any_of(instruction->users(), [&](const HloInstruction* user) { return in_range_instructions.count(user) != 0; }); }; [&](const HloInstruction* user) { return in_range_instructions.count(user) != 0; }); absl::Status MorphModuleWithInstructions(HloModule* module, size_t num_instructions) { std::vector<HloInstruction*> ordered_instructions = GetModifiedInstructionPostOrder(module->entry_computation()); HloInstruction* const* instructions_begin = &ordered_instructions.front(); return MorphModuleWithInstructions( module, absl::MakeSpan(instructions_begin, num_instructions)); } absl::Status MorphModuleWithLiterals( HloModule* module, absl::flat_hash_map<std::string, Literal> literal_map) { HloComputation* entry_computation = module->entry_computation(); // Iterate over instructions, as lookup by instruction name is linear. absl::flat_hash_map<HloInstruction*, Literal> replace_map; for (HloInstruction* instruction : entry_computation->instructions()) { auto it = literal_map.find(instruction->name()); if (it != literal_map.end()) { replace_map.emplace(instruction, std::move(it->second)); } } for (auto& [instruction, literal] : replace_map) { if (!instruction->IsDead()) { HloInstruction* new_instruction = entry_computation->AddInstruction( HloInstruction::CreateConstant(std::move(literal))); absl::Status replace_status = entry_computation->ReplaceInstruction(instruction, new_instruction); TF_RETURN_IF_ERROR(replace_status); } } xla::HloDCE dce; absl::StatusOr<bool> dce_status = dce.Run(module); return dce_status.status(); } bool InstructionNotReplaceableWithConstant(HloInstruction* instruction) { return instruction->shape().is_dynamic() || instruction->opcode() == HloOpcode::kConstant || instruction->opcode() == HloOpcode::kTuple || instruction->opcode() == HloOpcode::kParameter; } absl::StatusOr<bool> HloBisectState::ShouldProcess() { // Running the unmodified module should trigger the bug checker. return RunModule(*module_); } absl::StatusOr<bool> HloBisectState::TrimEntryComputation() { bool changed_in_loop = false; bool changed = false; for (int iter = 0; changed || iter < 2; iter++) { if (iter % 2 == 0) { VLOG(2) << "Trimming by outputs, iteration " << iter; TF_ASSIGN_OR_RETURN(changed, TrimByOutputs()); } else { VLOG(2) << "Trimming by instructions, iteration " << iter; TF_ASSIGN_OR_RETURN(changed, TrimByInstructions()); } changed_in_loop |= changed; } VLOG(2) << "Trimming by replacing instructions with literals"; TF_ASSIGN_OR_RETURN(changed, TrimByUsingConstants()); VLOG(2) << "Final module: " << module_->ToString(); return changed || changed_in_loop; } VLOG(2) << "Trimming by outputs, iteration " << iter; VLOG(2) << "Trimming by instructions, iteration " << iter; VLOG(2) << "Trimming by replacing instructions with literals"; VLOG(2) << "Final module: " << module_->ToString(); std::unique_ptr<xla::HloModule>&& HloBisectState::GetResult() { return std::move(module_); } absl::StatusOr<bool> HloBisectState::RunModule(const HloModule& module) { VLOG(3) << "Modified module: " << module.ToString(); // Run the modified module with the bug checker. absl::StatusOr<bool> bug_result = bug_checker_->Run(module); TF_RETURN_IF_ERROR(bug_result.status()); VLOG(3) << "Bug checker result: " << bug_result.value(); // Update foldable instructions data. if (!bug_result.value()) { for (HloInstruction* instr : module.entry_computation()->instructions()) { foldable_instructions_.emplace(instr->name()); } for (auto& [key, value] : bug_checker_->GetResults()) { foldable_instructions_values_[key] = std::move(value); } } return bug_result; } VLOG(3) << "Modified module: " << module.ToString(); VLOG(3) << "Bug checker result: " << bug_result.value(); absl::StatusOr<bool> HloBisectState::TrimByOutputs() { // Only available if the root instruction is a tuple. HloInstruction* root_instruction = module_->entry_computation()->root_instruction(); if (root_instruction->opcode() != HloOpcode::kTuple || root_instruction->operand_count() < 2) { return false; } // Run the modified module and return the error state. auto run_modified = [&](int64_t start, int64_t end) -> absl::StatusOr<bool> { std::unique_ptr<HloModule> new_module = module_->Clone(/*suffix=*/""); HloInstruction* const* new_operands = new_module->entry_computation()->root_instruction()->operands().begin(); TF_RETURN_IF_ERROR(MorphModuleWithOutputs( new_module.get(), absl::MakeSpan(new_operands + start, end - start + 1))); return RunModule(*new_module); }; // Binary search for the operands range that exhibits a bug. int64_t bisect_low = 0; int64_t bisect_high = root_instruction->operand_count() - 1; while (bisect_low < bisect_high) { int64_t cur = bisect_low + (bisect_high - bisect_low) / 2; VLOG(2) << "Number of outputs: " << (cur - bisect_low + 1) << " [" << bisect_low << ".." << cur << "]"; TF_ASSIGN_OR_RETURN(bool has_bug, run_modified(bisect_low, cur)); if (has_bug) { bisect_high = cur; } else { TF_ASSIGN_OR_RETURN(has_bug, run_modified(cur + 1, bisect_high)); if (has_bug) { bisect_low = cur + 1; } else { break; } } } // Update the current module and verify that the bug is present, if changed. bool changed = (bisect_high - bisect_low) < (root_instruction->operand_count() - 1); if (changed) { TF_RETURN_IF_ERROR(MorphModuleWithOutputs( module_.get(), absl::MakeSpan(root_instruction->operands().begin() + bisect_low, bisect_high - bisect_low + 1))); TF_RETURN_IF_ERROR(ExpectModuleIsBuggy()); } return changed; } auto run_modified = [&](int64_t start, int64_t end) -> absl::StatusOr<bool> { std::unique_ptr<HloModule> new_module = module_->Clone(/*suffix=*/""); HloInstruction* const* new_operands = new_module->entry_computation()->root_instruction()->operands().begin(); TF_RETURN_IF_ERROR(MorphModuleWithOutputs( new_module.get(), absl::MakeSpan(new_operands + start, end - start + 1))); return RunModule(*new_module); }; VLOG(2) << "Number of outputs: " << (cur - bisect_low + 1) << " [" absl::StatusOr<bool> HloBisectState::TrimByInstructions() { HloComputation* computation = module_->entry_computation(); // If the root instruction is a tuple, exclude it from the bisect range. int64_t upper_bound = computation->instruction_count() - computation->root_instruction()->shape().IsTuple(); // Binary search for the instructions range that exhibits a bug. int64_t bisect_low = computation->num_parameters() - 1; int64_t bisect_high = upper_bound; while (bisect_low + 1 < bisect_high) { int64_t cur = bisect_low + (bisect_high - bisect_low) / 2; VLOG(2) << "Number of instructions: " << cur << " (of " << computation->instruction_count() << ")"; std::unique_ptr<HloModule> new_module = module_->Clone(/*suffix=*/""); TF_RETURN_IF_ERROR(MorphModuleWithInstructions(new_module.get(), cur)); TF_ASSIGN_OR_RETURN(bool has_bug, RunModule(*new_module)); if (has_bug) { bisect_high = cur; } else { bisect_low = cur; } } // Sanity check for the bug checker. if (bisect_high == computation->num_parameters()) { return Internal( "The checker fails on an empty computation! Something is not right. " "Can't bisect."); } // Update the current module and verify that the bug is present, if changed. bool changed = bisect_high < upper_bound; if (changed) { TF_RETURN_IF_ERROR(MorphModuleWithInstructions(module_.get(), bisect_high)); TF_RETURN_IF_ERROR(ExpectModuleIsBuggy()); } return changed; } VLOG(2) << "Number of instructions: " << cur << " (of " absl::StatusOr<bool> HloBisectState::TrimByUsingConstants() { // Use random literals for the instructions which do not trigger the bug // checker and also didn't get a definitive value from it. absl::flat_hash_map<std::string, Literal> literal_map; int64_t random_literals_count = 0; for (HloInstruction* instr : module_->entry_computation()->instructions()) { if (InstructionNotReplaceableWithConstant(instr)) { continue; } if (foldable_instructions_values_.contains(instr->name())) { auto it = foldable_instructions_values_.extract(instr->name()); literal_map.insert(std::move(it)); } else if (foldable_instructions_.contains(instr->name())) { absl::StatusOr<Literal> literal_status = MakeFakeLiteral(instr->shape()); TF_RETURN_IF_ERROR(literal_status.status()); literal_map[instr->name()] = std::move(literal_status).value(); ++random_literals_count; } } VLOG(2) << "Number of literals: " << literal_map.size() << " (random: " << random_literals_count << ")"; // Replace instructions with constants and run the bug checker. // It is possible that the random literals will make the bug disappear, in // which case the module will not get reduced. std::unique_ptr<HloModule> new_module = module_->Clone(/*suffix=*/""); TF_RETURN_IF_ERROR( MorphModuleWithLiterals(new_module.get(), std::move(literal_map))); TF_ASSIGN_OR_RETURN(bool has_bug, RunModule(*new_module)); if (has_bug) { std::swap(module_, new_module); } return has_bug; } VLOG(2) << "Number of literals: " << literal_map.size() absl::Status HloBisectState::ExpectModuleIsBuggy() { // Verify that the current module has a bug. TF_ASSIGN_OR_RETURN(bool has_bug, RunModule(*module_)); if (has_bug) { return absl::OkStatus(); } // Check for the bug checker stability. const int retry_count = 5; int bug_count = 0; for (int i = 0; i < retry_count; i++) { TF_ASSIGN_OR_RETURN(has_bug, bug_checker_->Run(*module_)); if (has_bug) { bug_count++; } } if (bug_count != 0) { return InternalStrCat("The checker is non deterministic! (only ", bug_count, " failures seen in ", (retry_count + 1), " runs)"); } return Internal("We \"lost\" the bug while bisecting!"); }
#include "xla/tools/hlo_bisect/hlo_bisect_state.h" #include <initializer_list> #include <string> #include <utility> #include <vector> #include "absl/algorithm/container.h" #include "absl/status/statusor.h" #include "xla/hlo/ir/hlo_module.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/literal.h" #include "xla/service/pattern_matcher.h" #include "xla/service/pattern_matcher_gmock.h" #include "xla/tests/hlo_test_base.h" TEST_F(HloBisectStateTest, TrimByUsingReferenceConstants) { class TestBugSearchWithReferenceConstants : public TestBugSearch { public: TestBugSearchWithReferenceConstants() : TestBugSearch({HloOpcode::kPower}) {} absl::flat_hash_map<std::string, Literal> GetResults() override { absl::flat_hash_map<std::string, Literal> results; results["a"] = CreateLiteral(2.0f); results["b"] = CreateLiteral(3.0f); return results; } }; const char* kModuleStr = R"( HloModule test_module ENTRY test_computation { p1 = f32[] parameter(0) p2 = f32[] parameter(1) a = f32[] multiply(p1, p2) b = f32[] add(p1, p2) ROOT result = f32[] power(a, b) } )"; TF_ASSERT_OK_AND_ASSIGN(auto module, ParseAndReturnVerifiedModule(kModuleStr)); TestBugSearchWithReferenceConstants bug_checker; HloBisectState bisect(std::move(module), &bug_checker); TF_ASSERT_OK_AND_ASSIGN(bool changed, bisect.TrimEntryComputation()); EXPECT_TRUE(changed); auto reduced_module = std::move(bisect).GetResult(); EXPECT_THAT(reduced_module->entry_computation()->root_instruction(), GmockMatch(m::Power(m::Constant(), m::Constant()))); }
HloControlFlowFlatteningTest_AllGather
xla/tools/hlo_control_flow_flattening_test.cc
HloInstruction* CreateConstant(const Shape& shape, HloComputation* computation) { if (shape.IsTuple()) { std::vector<HloInstruction*> tuple_arguments(shape.tuple_shapes_size()); for (int index = 0; index < shape.tuple_shapes_size(); ++index) { tuple_arguments[index] = CreateConstant(shape.tuple_shapes(index), computation); } return computation->AddInstruction( HloInstruction::CreateTuple(tuple_arguments)); } else { return computation->AddInstruction( HloInstruction::CreateConstant(Literal::CreateFromShape(shape))); } } void PrintSubexpression(HloInstruction* inst, int depth) { if (depth == 0) { return; } for (auto* operand : inst->operands()) { PrintSubexpression(operand, depth - 1); } VLOG(2) << inst->ToString(); } VLOG(2) << inst->ToString(); bool IsConstantScalarInt(const HloInstruction* inst) { return inst->opcode() == HloOpcode::kConstant && ShapeUtil::IsEffectiveScalar(inst->shape()) && inst->shape().IsInteger(); } bool IsNotContainedInLoop(const HloInstruction& while_hlo, const CallGraph& call_graph) { const HloComputation* computation = while_hlo.parent(); while (!computation->IsEntryComputation()) { auto& node = call_graph.GetNode(computation); CHECK_EQ(node.caller_callsites().size(), 1) << "The module is not flattened!"; auto& callsite = node.caller_callsites()[0]; if (callsite.instruction()->opcode() == HloOpcode::kWhile) { // Another while loop has been found traversing up the call tree. return false; } computation = callsite.instruction()->parent(); } // No calling while loops were found. return true; } int GetLoopBound(const HloInstruction& while_hlo, const int default_loop_count, const int max_loop_count) { HloInstruction* condition = while_hlo.while_condition()->root_instruction(); if (condition->opcode() == HloOpcode::kCompare) { int64_t value = 0; Comparison::Direction cmp = condition->comparison_direction(); if ((cmp == Comparison::Direction::kLt || cmp == Comparison::Direction::kLe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(1))) { value = *condition->operand(1)->literal().GetFirstInteger(); } else if ((cmp == Comparison::Direction::kGt || cmp == Comparison::Direction::kGe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(0))) { value = *condition->operand(0)->literal().GetFirstInteger(); } if (value > 0) { // Caps to a max loop count to avoid long execution times. return std::min(value, static_cast<int64_t>(max_loop_count)); } } return default_loop_count; } int GetLoopBoundWithOuterLoopMax(const HloInstruction& while_hlo, const CallGraph& call_graph, const int default_loop_count, const int max_outer_loop_count, const int max_loop_count) { int loop_bound = GetLoopBound(while_hlo, default_loop_count, max_loop_count); if (loop_bound > max_outer_loop_count) { // First does the inexpensive loop bound check to avoid as many // expensive graph traversals in IsNotContainedInLoop as possible. if (IsNotContainedInLoop(while_hlo, call_graph)) { return max_outer_loop_count; } } return loop_bound; } absl::Status HloControlFlowFlattening::FlattenWhileLoop( HloInstruction* while_hlo, const CallGraph& call_graph) const { CHECK_EQ(while_hlo->opcode(), HloOpcode::kWhile); HloComputation* computation = while_hlo->parent(); // Add a new induction variable. HloInstruction* initialization = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(0))); // Create a new while operand with the induction variable added. HloInstruction* old_tuple = while_hlo->mutable_operand(0); HloInstruction* new_tuple = TupleUtil::AppendSuffix(old_tuple, {initialization}); int new_tuple_size = new_tuple->shape().tuple_shapes().size(); TF_RETURN_IF_ERROR(while_hlo->ReplaceOperandWithDifferentShape(0, new_tuple)); auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; // Replace the given tuple-shaped instruction of size N in each of its // non-get-tuple-element users with a new tuple instruction which has the // first N - 1 elements. auto replace_non_gte_users = [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; { // Add the new variable to the while loop condition. HloComputation* condition = while_hlo->while_condition(); TF_RETURN_IF_ERROR(change_op_shape(condition->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(condition->parameter_instruction(0)).status()); if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); PrintSubexpression(condition->root_instruction(), /*depth=*/3); } const int loop_bound = GetLoopBoundWithOuterLoopMax( *while_hlo, call_graph, while_execution_count_, max_outer_loop_count_, max_loop_count_); VLOG(1) << "loop_bound = " << loop_bound; HloInstruction* limit = condition->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(loop_bound))); Shape shape = initialization->shape(); HloInstruction* induction_variable = condition->AddInstruction(HloInstruction::CreateGetTupleElement( shape, condition->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* compare = condition->AddInstruction(HloInstruction::CreateCompare( ShapeUtil::MakeShape(PRED, {}), induction_variable, limit, ComparisonDirection::kLt)); TF_RETURN_IF_ERROR( condition->ReplaceInstruction(condition->root_instruction(), compare)); } { // Add the new variable to the while loop body. HloComputation* body = while_hlo->while_body(); TF_RETURN_IF_ERROR(change_op_shape(body->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(body->parameter_instruction(0)).status()); HloInstruction* old_root = body->root_instruction(); Shape shape = initialization->shape(); HloInstruction* induction_variable = body->AddInstruction(HloInstruction::CreateGetTupleElement( shape, body->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* increment = body->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(1))); induction_variable = body->AddInstruction(HloInstruction::CreateBinary( shape, HloOpcode::kAdd, induction_variable, increment)); HloInstruction* new_root = TupleUtil::AppendSuffix(old_root, {induction_variable}); body->set_root_instruction(new_root, /*accept_different_shape=*/true); } // Snapshot the users of while hlo before we add new users. std::vector<HloInstruction*> while_users(while_hlo->users().begin(), while_hlo->users().end()); // Take care of the users of this while loop. TF_RETURN_IF_ERROR(change_op_shape(while_hlo)); TF_ASSIGN_OR_RETURN(HloInstruction * prefix, replace_non_gte_users(while_hlo)); // If the while loop had been the root of its computation, make the prefix new // root. if (while_hlo->parent()->root_instruction() == while_hlo) { // We need to set accept_different_shape=true to reset the root shape to the // original, because we have already changed the shape of the old root // (while). if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix(while_hlo, new_tuple_size - 1); } while_hlo->parent()->set_root_instruction(prefix, /*accept_different_shape=*/true); } return absl::OkStatus(); } auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); VLOG(1) << "loop_bound = " << loop_bound; absl::Status HloControlFlowFlattening::RemoveInfeed( HloInstruction* infeed_hlo) const { CHECK_EQ(infeed_hlo->opcode(), HloOpcode::kInfeed); HloComputation* computation = infeed_hlo->parent(); CHECK_EQ(infeed_hlo->shape().tuple_shapes_size(), 2); const Shape& infeed_shape = ShapeUtil::GetSubshape(infeed_hlo->shape(), {0}); HloInstruction* custom_call = computation->AddInstruction( HloInstruction::CreateCustomCall(infeed_shape, {}, kNopCustomCallTarget)); // Create a new tuple consisting of the constant and the token that was // originally the operand of infeed, and replace the infeed operation. auto new_tuple = HloInstruction::CreateTuple( {custom_call, infeed_hlo->mutable_operand(0)}); TF_RETURN_IF_ERROR( computation->ReplaceWithNewInstruction(infeed_hlo, std::move(new_tuple))); custom_call->SetAndSanitizeName(infeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveRecvAndRecvDone( HloInstruction* recv_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(recv_done->opcode(), HloOpcode::kRecvDone); CHECK_EQ(recv_done->operand_count(), 1); HloInstruction* recv = recv_done->mutable_operand(0); CHECK_EQ(recv->opcode(), HloOpcode::kRecv); HloComputation* computation = recv_done->parent(); CHECK_EQ(recv_done->shape().tuple_shapes_size(), 2); HloModule* module = computation->parent(); HloInstruction* custom_call_recv = computation->AddInstruction(HloInstruction::CreateCustomCall( recv->shape(), recv->operands(), kNopCustomCallTarget)); std::string original_recv_name(recv->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv, custom_call_recv); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(recv, custom_call_recv)); custom_call_recv->SetAndSanitizeName(original_recv_name); std::string original_recv_done_name(recv_done->name()); HloInstruction* custom_call_recv_done = computation->AddInstruction( HloInstruction::CreateCustomCall( recv_done->shape(), recv_done->operands(), kNopCustomCallTarget), recv_done->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv_done, custom_call_recv_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(recv_done, custom_call_recv_done)); custom_call_recv_done->SetAndSanitizeName(original_recv_done_name); return std::make_pair(custom_call_recv, custom_call_recv_done); } absl::Status HloControlFlowFlattening::RemoveOutfeed( HloInstruction* outfeed_hlo) const { CHECK_EQ(outfeed_hlo->opcode(), HloOpcode::kOutfeed); HloComputation* computation = outfeed_hlo->parent(); // Replace the outfeed with a no-op custom call with side effect to ensure the // operands aren't DCE'd. HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( outfeed_hlo->shape(), outfeed_hlo->operands(), kNopReturnTokenCustomCallTarget)); Cast<HloCustomCallInstruction>(custom_call) ->set_custom_call_has_side_effect(true); // For SPMD graphs, partitioner requires that side-effecting custom calls have // a sharding that is non-replicated. custom_call->set_sharding(HloSharding::Manual()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(outfeed_hlo, custom_call)); custom_call->SetAndSanitizeName(outfeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveSendAndSendDone( HloInstruction* send_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(send_done->opcode(), HloOpcode::kSendDone); CHECK_EQ(send_done->operand_count(), 1); HloInstruction* send = send_done->mutable_operand(0); CHECK_EQ(send->opcode(), HloOpcode::kSend); HloComputation* computation = send_done->parent(); HloModule* module = computation->parent(); HloInstruction* custom_call_send = computation->AddInstruction(HloInstruction::CreateCustomCall( send->shape(), send->operands(), kNopCustomCallTarget)); std::string original_send_name(send->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send, custom_call_send); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(send, custom_call_send)); custom_call_send->SetAndSanitizeName(original_send_name); HloInstruction* custom_call_send_done = computation->AddInstruction(HloInstruction::CreateCustomCall( send_done->shape(), send_done->operands(), kNopReturnTokenCustomCallTarget)); std::string original_send_done_name(send_done->name()); Cast<HloCustomCallInstruction>(custom_call_send_done) ->set_custom_call_has_side_effect(true); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send_done, custom_call_send_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(send_done, custom_call_send_done)); custom_call_send_done->SetAndSanitizeName(original_send_done_name); return std::make_pair(custom_call_send, custom_call_send_done); } absl::StatusOr<HloInstruction*> HloControlFlowFlattening::RemoveCollective( HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( hlo->shape(), hlo->operands(), kNopCustomCallTarget)); // Copy backend config. This is necessary for a collective op in megacore // fusion. custom_call->CopyBackendConfigFrom(hlo); HloModule* module = computation->parent(); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, hlo, custom_call); } std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, custom_call)); custom_call->SetAndSanitizeName(original_op_name); return custom_call; } absl::Status HloControlFlowFlattening::RemoveId(HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* zero = CreateConstant(hlo->shape(), computation); std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, zero)); zero->SetAndSanitizeName(original_op_name); return absl::OkStatus(); } absl::StatusOr<bool> HloControlFlowFlattening::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { auto call_graph = CallGraph::Build(module); bool changed = false; absl::flat_hash_set<HloInstruction*> removed; for (HloComputation* computation : module->computations(execution_threads)) { // Do not change computations that are wrapped by async calls. Instead we // remove the async callers if needed. if (computation->IsAsyncComputation()) { continue; } for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (removed.contains(instruction)) { // Skip the instruction if it is already removed. continue; } if (flatten_while_loop_ && instruction->opcode() == HloOpcode::kWhile) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(FlattenWhileLoop(instruction, *call_graph)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kInfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveInfeed(instruction)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kOutfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveOutfeed(instruction)); changed = true; } else if (instruction->opcode() == HloOpcode::kSendDone) { auto send_done_instruction = DynCast<HloSendDoneInstruction>(instruction); CHECK(send_done_instruction); if (remove_comm_ || (remove_host_transfer_ && send_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveSendAndSendDone(instruction, &removed).status()); changed = true; } } else if (instruction->opcode() == HloOpcode::kRecvDone) { auto recv_done_instruction = DynCast<HloRecvDoneInstruction>(instruction); CHECK(recv_done_instruction); if (remove_comm_ || (remove_host_transfer_ && recv_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveRecvAndRecvDone(instruction, &removed).status()); changed = true; } } else if (remove_comm_ && IsCollective(instruction) && !instruction->parent()->IsFusionComputation() && (instruction->opcode() != HloOpcode::kAsyncStart && instruction->opcode() != HloOpcode::kAsyncUpdate)) { // We do not remove kAsyncStart or kAsyncUpdate here since we expect // them to be removed as a part of the async chain above. // We should remove the async chain all together because the async // wrapped computation is only associated with the AsyncStart. So we // need to refer to the AsyncStart in order to determine whether // the Done or the Update wraps a collective. if (instruction->opcode() == HloOpcode::kAsyncDone) { while (instruction->opcode() == HloOpcode::kAsyncDone || instruction->opcode() == HloOpcode::kAsyncUpdate || instruction->opcode() == HloOpcode::kAsyncStart) { HloInstruction* operand = instruction->mutable_operand(0); VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); instruction = operand; } } else { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); } changed = true; } else if (remove_comm_ && (instruction->opcode() == HloOpcode::kPartitionId || instruction->opcode() == HloOpcode::kReplicaId || (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == "SliceId"))) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveId(instruction)); changed = true; } } } HloDCE hlo_dce; TF_ASSIGN_OR_RETURN(bool dce_changed, hlo_dce.Run(module, execution_threads)); changed |= dce_changed; // Fix the schedule if the module was scheduled. if (changed && module->has_schedule()) { TF_RETURN_IF_ERROR(module->schedule().Update()); } XLA_VLOG_LINES(3, module->ToString()); return changed; } VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); XLA_VLOG_LINES(3, module->ToString());
#include "xla/tools/hlo_control_flow_flattening.h" #include <memory> #include <utility> #include "absl/strings/str_replace.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/collective_ops_utils.h" #include "xla/service/despecializer.h" #include "xla/service/hlo_verifier.h" #include "xla/service/spmd/spmd_partitioner.h" #include "xla/tests/hlo_test_base.h" #include "tsl/lib/core/status_test_util.h" class HloControlFlowFlatteningTest : public HloTestBase { public: absl::StatusOr<std::unique_ptr<HloModule>> PartitionComputation( std::unique_ptr<VerifiedHloModule> hlo_module, int64_t num_devices = 2) { spmd::SpmdPartitionerOptions options; auto collective_ops_creator = spmd::GetDefaultCollectiveOpsCreator(num_devices, /*num_replicas=*/1); collective_ops_creator.create_cross_partition_all_gather = nullptr; HloModuleConfig config = GetModuleConfigForTest(); config.set_use_spmd_partitioning(true); config.set_num_partitions(num_devices); HloPassPipeline pass("spmd-partitioning"); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); pass.AddPass<spmd::SpmdPartitioner>(num_devices, /*num_replicas=*/1, options, collective_ops_creator); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); TF_RETURN_IF_ERROR(pass.Run(hlo_module.get()).status()); return absl::StatusOr<std::unique_ptr<HloModule>>(std::move(hlo_module)); } }; TEST_F(HloControlFlowFlatteningTest, AllGather) { absl::string_view hlo_string = R"( HloModule AllGather ENTRY AllGather { input = f32[128,32]{0,1} parameter(0) ROOT ag = f32[128,128]{0,1} all-gather(input), replica_groups={}, dimensions={1} } )"; TF_ASSERT_OK_AND_ASSIGN(auto module, ParseAndReturnVerifiedModule(hlo_string)); HloControlFlowFlattening flattening( HloControlFlowFlattening::Options{/*while_execution_count=*/3}); EXPECT_TRUE(flattening.Run(module.get()).value()); TF_ASSERT_OK(HloVerifier(/*layout_sensitive=*/true, /*allow_mixed_precision=*/true) .Run(module.get()) .status()); EXPECT_THAT(module->entry_computation()->root_instruction(), op::CustomCall(op::Parameter(0))); EXPECT_EQ(module->entry_computation()->root_instruction()->name(), "ag"); }
HloControlFlowFlatteningTest_AllGatherStartAndDone
xla/tools/hlo_control_flow_flattening_test.cc
HloInstruction* CreateConstant(const Shape& shape, HloComputation* computation) { if (shape.IsTuple()) { std::vector<HloInstruction*> tuple_arguments(shape.tuple_shapes_size()); for (int index = 0; index < shape.tuple_shapes_size(); ++index) { tuple_arguments[index] = CreateConstant(shape.tuple_shapes(index), computation); } return computation->AddInstruction( HloInstruction::CreateTuple(tuple_arguments)); } else { return computation->AddInstruction( HloInstruction::CreateConstant(Literal::CreateFromShape(shape))); } } void PrintSubexpression(HloInstruction* inst, int depth) { if (depth == 0) { return; } for (auto* operand : inst->operands()) { PrintSubexpression(operand, depth - 1); } VLOG(2) << inst->ToString(); } VLOG(2) << inst->ToString(); bool IsConstantScalarInt(const HloInstruction* inst) { return inst->opcode() == HloOpcode::kConstant && ShapeUtil::IsEffectiveScalar(inst->shape()) && inst->shape().IsInteger(); } bool IsNotContainedInLoop(const HloInstruction& while_hlo, const CallGraph& call_graph) { const HloComputation* computation = while_hlo.parent(); while (!computation->IsEntryComputation()) { auto& node = call_graph.GetNode(computation); CHECK_EQ(node.caller_callsites().size(), 1) << "The module is not flattened!"; auto& callsite = node.caller_callsites()[0]; if (callsite.instruction()->opcode() == HloOpcode::kWhile) { // Another while loop has been found traversing up the call tree. return false; } computation = callsite.instruction()->parent(); } // No calling while loops were found. return true; } int GetLoopBound(const HloInstruction& while_hlo, const int default_loop_count, const int max_loop_count) { HloInstruction* condition = while_hlo.while_condition()->root_instruction(); if (condition->opcode() == HloOpcode::kCompare) { int64_t value = 0; Comparison::Direction cmp = condition->comparison_direction(); if ((cmp == Comparison::Direction::kLt || cmp == Comparison::Direction::kLe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(1))) { value = *condition->operand(1)->literal().GetFirstInteger(); } else if ((cmp == Comparison::Direction::kGt || cmp == Comparison::Direction::kGe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(0))) { value = *condition->operand(0)->literal().GetFirstInteger(); } if (value > 0) { // Caps to a max loop count to avoid long execution times. return std::min(value, static_cast<int64_t>(max_loop_count)); } } return default_loop_count; } int GetLoopBoundWithOuterLoopMax(const HloInstruction& while_hlo, const CallGraph& call_graph, const int default_loop_count, const int max_outer_loop_count, const int max_loop_count) { int loop_bound = GetLoopBound(while_hlo, default_loop_count, max_loop_count); if (loop_bound > max_outer_loop_count) { // First does the inexpensive loop bound check to avoid as many // expensive graph traversals in IsNotContainedInLoop as possible. if (IsNotContainedInLoop(while_hlo, call_graph)) { return max_outer_loop_count; } } return loop_bound; } absl::Status HloControlFlowFlattening::FlattenWhileLoop( HloInstruction* while_hlo, const CallGraph& call_graph) const { CHECK_EQ(while_hlo->opcode(), HloOpcode::kWhile); HloComputation* computation = while_hlo->parent(); // Add a new induction variable. HloInstruction* initialization = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(0))); // Create a new while operand with the induction variable added. HloInstruction* old_tuple = while_hlo->mutable_operand(0); HloInstruction* new_tuple = TupleUtil::AppendSuffix(old_tuple, {initialization}); int new_tuple_size = new_tuple->shape().tuple_shapes().size(); TF_RETURN_IF_ERROR(while_hlo->ReplaceOperandWithDifferentShape(0, new_tuple)); auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; // Replace the given tuple-shaped instruction of size N in each of its // non-get-tuple-element users with a new tuple instruction which has the // first N - 1 elements. auto replace_non_gte_users = [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; { // Add the new variable to the while loop condition. HloComputation* condition = while_hlo->while_condition(); TF_RETURN_IF_ERROR(change_op_shape(condition->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(condition->parameter_instruction(0)).status()); if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); PrintSubexpression(condition->root_instruction(), /*depth=*/3); } const int loop_bound = GetLoopBoundWithOuterLoopMax( *while_hlo, call_graph, while_execution_count_, max_outer_loop_count_, max_loop_count_); VLOG(1) << "loop_bound = " << loop_bound; HloInstruction* limit = condition->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(loop_bound))); Shape shape = initialization->shape(); HloInstruction* induction_variable = condition->AddInstruction(HloInstruction::CreateGetTupleElement( shape, condition->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* compare = condition->AddInstruction(HloInstruction::CreateCompare( ShapeUtil::MakeShape(PRED, {}), induction_variable, limit, ComparisonDirection::kLt)); TF_RETURN_IF_ERROR( condition->ReplaceInstruction(condition->root_instruction(), compare)); } { // Add the new variable to the while loop body. HloComputation* body = while_hlo->while_body(); TF_RETURN_IF_ERROR(change_op_shape(body->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(body->parameter_instruction(0)).status()); HloInstruction* old_root = body->root_instruction(); Shape shape = initialization->shape(); HloInstruction* induction_variable = body->AddInstruction(HloInstruction::CreateGetTupleElement( shape, body->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* increment = body->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(1))); induction_variable = body->AddInstruction(HloInstruction::CreateBinary( shape, HloOpcode::kAdd, induction_variable, increment)); HloInstruction* new_root = TupleUtil::AppendSuffix(old_root, {induction_variable}); body->set_root_instruction(new_root, /*accept_different_shape=*/true); } // Snapshot the users of while hlo before we add new users. std::vector<HloInstruction*> while_users(while_hlo->users().begin(), while_hlo->users().end()); // Take care of the users of this while loop. TF_RETURN_IF_ERROR(change_op_shape(while_hlo)); TF_ASSIGN_OR_RETURN(HloInstruction * prefix, replace_non_gte_users(while_hlo)); // If the while loop had been the root of its computation, make the prefix new // root. if (while_hlo->parent()->root_instruction() == while_hlo) { // We need to set accept_different_shape=true to reset the root shape to the // original, because we have already changed the shape of the old root // (while). if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix(while_hlo, new_tuple_size - 1); } while_hlo->parent()->set_root_instruction(prefix, /*accept_different_shape=*/true); } return absl::OkStatus(); } auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); VLOG(1) << "loop_bound = " << loop_bound; absl::Status HloControlFlowFlattening::RemoveInfeed( HloInstruction* infeed_hlo) const { CHECK_EQ(infeed_hlo->opcode(), HloOpcode::kInfeed); HloComputation* computation = infeed_hlo->parent(); CHECK_EQ(infeed_hlo->shape().tuple_shapes_size(), 2); const Shape& infeed_shape = ShapeUtil::GetSubshape(infeed_hlo->shape(), {0}); HloInstruction* custom_call = computation->AddInstruction( HloInstruction::CreateCustomCall(infeed_shape, {}, kNopCustomCallTarget)); // Create a new tuple consisting of the constant and the token that was // originally the operand of infeed, and replace the infeed operation. auto new_tuple = HloInstruction::CreateTuple( {custom_call, infeed_hlo->mutable_operand(0)}); TF_RETURN_IF_ERROR( computation->ReplaceWithNewInstruction(infeed_hlo, std::move(new_tuple))); custom_call->SetAndSanitizeName(infeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveRecvAndRecvDone( HloInstruction* recv_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(recv_done->opcode(), HloOpcode::kRecvDone); CHECK_EQ(recv_done->operand_count(), 1); HloInstruction* recv = recv_done->mutable_operand(0); CHECK_EQ(recv->opcode(), HloOpcode::kRecv); HloComputation* computation = recv_done->parent(); CHECK_EQ(recv_done->shape().tuple_shapes_size(), 2); HloModule* module = computation->parent(); HloInstruction* custom_call_recv = computation->AddInstruction(HloInstruction::CreateCustomCall( recv->shape(), recv->operands(), kNopCustomCallTarget)); std::string original_recv_name(recv->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv, custom_call_recv); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(recv, custom_call_recv)); custom_call_recv->SetAndSanitizeName(original_recv_name); std::string original_recv_done_name(recv_done->name()); HloInstruction* custom_call_recv_done = computation->AddInstruction( HloInstruction::CreateCustomCall( recv_done->shape(), recv_done->operands(), kNopCustomCallTarget), recv_done->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv_done, custom_call_recv_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(recv_done, custom_call_recv_done)); custom_call_recv_done->SetAndSanitizeName(original_recv_done_name); return std::make_pair(custom_call_recv, custom_call_recv_done); } absl::Status HloControlFlowFlattening::RemoveOutfeed( HloInstruction* outfeed_hlo) const { CHECK_EQ(outfeed_hlo->opcode(), HloOpcode::kOutfeed); HloComputation* computation = outfeed_hlo->parent(); // Replace the outfeed with a no-op custom call with side effect to ensure the // operands aren't DCE'd. HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( outfeed_hlo->shape(), outfeed_hlo->operands(), kNopReturnTokenCustomCallTarget)); Cast<HloCustomCallInstruction>(custom_call) ->set_custom_call_has_side_effect(true); // For SPMD graphs, partitioner requires that side-effecting custom calls have // a sharding that is non-replicated. custom_call->set_sharding(HloSharding::Manual()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(outfeed_hlo, custom_call)); custom_call->SetAndSanitizeName(outfeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveSendAndSendDone( HloInstruction* send_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(send_done->opcode(), HloOpcode::kSendDone); CHECK_EQ(send_done->operand_count(), 1); HloInstruction* send = send_done->mutable_operand(0); CHECK_EQ(send->opcode(), HloOpcode::kSend); HloComputation* computation = send_done->parent(); HloModule* module = computation->parent(); HloInstruction* custom_call_send = computation->AddInstruction(HloInstruction::CreateCustomCall( send->shape(), send->operands(), kNopCustomCallTarget)); std::string original_send_name(send->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send, custom_call_send); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(send, custom_call_send)); custom_call_send->SetAndSanitizeName(original_send_name); HloInstruction* custom_call_send_done = computation->AddInstruction(HloInstruction::CreateCustomCall( send_done->shape(), send_done->operands(), kNopReturnTokenCustomCallTarget)); std::string original_send_done_name(send_done->name()); Cast<HloCustomCallInstruction>(custom_call_send_done) ->set_custom_call_has_side_effect(true); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send_done, custom_call_send_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(send_done, custom_call_send_done)); custom_call_send_done->SetAndSanitizeName(original_send_done_name); return std::make_pair(custom_call_send, custom_call_send_done); } absl::StatusOr<HloInstruction*> HloControlFlowFlattening::RemoveCollective( HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( hlo->shape(), hlo->operands(), kNopCustomCallTarget)); // Copy backend config. This is necessary for a collective op in megacore // fusion. custom_call->CopyBackendConfigFrom(hlo); HloModule* module = computation->parent(); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, hlo, custom_call); } std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, custom_call)); custom_call->SetAndSanitizeName(original_op_name); return custom_call; } absl::Status HloControlFlowFlattening::RemoveId(HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* zero = CreateConstant(hlo->shape(), computation); std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, zero)); zero->SetAndSanitizeName(original_op_name); return absl::OkStatus(); } absl::StatusOr<bool> HloControlFlowFlattening::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { auto call_graph = CallGraph::Build(module); bool changed = false; absl::flat_hash_set<HloInstruction*> removed; for (HloComputation* computation : module->computations(execution_threads)) { // Do not change computations that are wrapped by async calls. Instead we // remove the async callers if needed. if (computation->IsAsyncComputation()) { continue; } for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (removed.contains(instruction)) { // Skip the instruction if it is already removed. continue; } if (flatten_while_loop_ && instruction->opcode() == HloOpcode::kWhile) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(FlattenWhileLoop(instruction, *call_graph)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kInfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveInfeed(instruction)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kOutfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveOutfeed(instruction)); changed = true; } else if (instruction->opcode() == HloOpcode::kSendDone) { auto send_done_instruction = DynCast<HloSendDoneInstruction>(instruction); CHECK(send_done_instruction); if (remove_comm_ || (remove_host_transfer_ && send_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveSendAndSendDone(instruction, &removed).status()); changed = true; } } else if (instruction->opcode() == HloOpcode::kRecvDone) { auto recv_done_instruction = DynCast<HloRecvDoneInstruction>(instruction); CHECK(recv_done_instruction); if (remove_comm_ || (remove_host_transfer_ && recv_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveRecvAndRecvDone(instruction, &removed).status()); changed = true; } } else if (remove_comm_ && IsCollective(instruction) && !instruction->parent()->IsFusionComputation() && (instruction->opcode() != HloOpcode::kAsyncStart && instruction->opcode() != HloOpcode::kAsyncUpdate)) { // We do not remove kAsyncStart or kAsyncUpdate here since we expect // them to be removed as a part of the async chain above. // We should remove the async chain all together because the async // wrapped computation is only associated with the AsyncStart. So we // need to refer to the AsyncStart in order to determine whether // the Done or the Update wraps a collective. if (instruction->opcode() == HloOpcode::kAsyncDone) { while (instruction->opcode() == HloOpcode::kAsyncDone || instruction->opcode() == HloOpcode::kAsyncUpdate || instruction->opcode() == HloOpcode::kAsyncStart) { HloInstruction* operand = instruction->mutable_operand(0); VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); instruction = operand; } } else { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); } changed = true; } else if (remove_comm_ && (instruction->opcode() == HloOpcode::kPartitionId || instruction->opcode() == HloOpcode::kReplicaId || (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == "SliceId"))) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveId(instruction)); changed = true; } } } HloDCE hlo_dce; TF_ASSIGN_OR_RETURN(bool dce_changed, hlo_dce.Run(module, execution_threads)); changed |= dce_changed; // Fix the schedule if the module was scheduled. if (changed && module->has_schedule()) { TF_RETURN_IF_ERROR(module->schedule().Update()); } XLA_VLOG_LINES(3, module->ToString()); return changed; } VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); XLA_VLOG_LINES(3, module->ToString());
#include "xla/tools/hlo_control_flow_flattening.h" #include <memory> #include <utility> #include "absl/strings/str_replace.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/collective_ops_utils.h" #include "xla/service/despecializer.h" #include "xla/service/hlo_verifier.h" #include "xla/service/spmd/spmd_partitioner.h" #include "xla/tests/hlo_test_base.h" #include "tsl/lib/core/status_test_util.h" class HloControlFlowFlatteningTest : public HloTestBase { public: absl::StatusOr<std::unique_ptr<HloModule>> PartitionComputation( std::unique_ptr<VerifiedHloModule> hlo_module, int64_t num_devices = 2) { spmd::SpmdPartitionerOptions options; auto collective_ops_creator = spmd::GetDefaultCollectiveOpsCreator(num_devices, /*num_replicas=*/1); collective_ops_creator.create_cross_partition_all_gather = nullptr; HloModuleConfig config = GetModuleConfigForTest(); config.set_use_spmd_partitioning(true); config.set_num_partitions(num_devices); HloPassPipeline pass("spmd-partitioning"); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); pass.AddPass<spmd::SpmdPartitioner>(num_devices, /*num_replicas=*/1, options, collective_ops_creator); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); TF_RETURN_IF_ERROR(pass.Run(hlo_module.get()).status()); return absl::StatusOr<std::unique_ptr<HloModule>>(std::move(hlo_module)); } };
HloControlFlowFlatteningTest_AllReduce
xla/tools/hlo_control_flow_flattening_test.cc
HloInstruction* CreateConstant(const Shape& shape, HloComputation* computation) { if (shape.IsTuple()) { std::vector<HloInstruction*> tuple_arguments(shape.tuple_shapes_size()); for (int index = 0; index < shape.tuple_shapes_size(); ++index) { tuple_arguments[index] = CreateConstant(shape.tuple_shapes(index), computation); } return computation->AddInstruction( HloInstruction::CreateTuple(tuple_arguments)); } else { return computation->AddInstruction( HloInstruction::CreateConstant(Literal::CreateFromShape(shape))); } } void PrintSubexpression(HloInstruction* inst, int depth) { if (depth == 0) { return; } for (auto* operand : inst->operands()) { PrintSubexpression(operand, depth - 1); } VLOG(2) << inst->ToString(); } VLOG(2) << inst->ToString(); bool IsConstantScalarInt(const HloInstruction* inst) { return inst->opcode() == HloOpcode::kConstant && ShapeUtil::IsEffectiveScalar(inst->shape()) && inst->shape().IsInteger(); } bool IsNotContainedInLoop(const HloInstruction& while_hlo, const CallGraph& call_graph) { const HloComputation* computation = while_hlo.parent(); while (!computation->IsEntryComputation()) { auto& node = call_graph.GetNode(computation); CHECK_EQ(node.caller_callsites().size(), 1) << "The module is not flattened!"; auto& callsite = node.caller_callsites()[0]; if (callsite.instruction()->opcode() == HloOpcode::kWhile) { // Another while loop has been found traversing up the call tree. return false; } computation = callsite.instruction()->parent(); } // No calling while loops were found. return true; } int GetLoopBound(const HloInstruction& while_hlo, const int default_loop_count, const int max_loop_count) { HloInstruction* condition = while_hlo.while_condition()->root_instruction(); if (condition->opcode() == HloOpcode::kCompare) { int64_t value = 0; Comparison::Direction cmp = condition->comparison_direction(); if ((cmp == Comparison::Direction::kLt || cmp == Comparison::Direction::kLe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(1))) { value = *condition->operand(1)->literal().GetFirstInteger(); } else if ((cmp == Comparison::Direction::kGt || cmp == Comparison::Direction::kGe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(0))) { value = *condition->operand(0)->literal().GetFirstInteger(); } if (value > 0) { // Caps to a max loop count to avoid long execution times. return std::min(value, static_cast<int64_t>(max_loop_count)); } } return default_loop_count; } int GetLoopBoundWithOuterLoopMax(const HloInstruction& while_hlo, const CallGraph& call_graph, const int default_loop_count, const int max_outer_loop_count, const int max_loop_count) { int loop_bound = GetLoopBound(while_hlo, default_loop_count, max_loop_count); if (loop_bound > max_outer_loop_count) { // First does the inexpensive loop bound check to avoid as many // expensive graph traversals in IsNotContainedInLoop as possible. if (IsNotContainedInLoop(while_hlo, call_graph)) { return max_outer_loop_count; } } return loop_bound; } absl::Status HloControlFlowFlattening::FlattenWhileLoop( HloInstruction* while_hlo, const CallGraph& call_graph) const { CHECK_EQ(while_hlo->opcode(), HloOpcode::kWhile); HloComputation* computation = while_hlo->parent(); // Add a new induction variable. HloInstruction* initialization = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(0))); // Create a new while operand with the induction variable added. HloInstruction* old_tuple = while_hlo->mutable_operand(0); HloInstruction* new_tuple = TupleUtil::AppendSuffix(old_tuple, {initialization}); int new_tuple_size = new_tuple->shape().tuple_shapes().size(); TF_RETURN_IF_ERROR(while_hlo->ReplaceOperandWithDifferentShape(0, new_tuple)); auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; // Replace the given tuple-shaped instruction of size N in each of its // non-get-tuple-element users with a new tuple instruction which has the // first N - 1 elements. auto replace_non_gte_users = [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; { // Add the new variable to the while loop condition. HloComputation* condition = while_hlo->while_condition(); TF_RETURN_IF_ERROR(change_op_shape(condition->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(condition->parameter_instruction(0)).status()); if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); PrintSubexpression(condition->root_instruction(), /*depth=*/3); } const int loop_bound = GetLoopBoundWithOuterLoopMax( *while_hlo, call_graph, while_execution_count_, max_outer_loop_count_, max_loop_count_); VLOG(1) << "loop_bound = " << loop_bound; HloInstruction* limit = condition->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(loop_bound))); Shape shape = initialization->shape(); HloInstruction* induction_variable = condition->AddInstruction(HloInstruction::CreateGetTupleElement( shape, condition->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* compare = condition->AddInstruction(HloInstruction::CreateCompare( ShapeUtil::MakeShape(PRED, {}), induction_variable, limit, ComparisonDirection::kLt)); TF_RETURN_IF_ERROR( condition->ReplaceInstruction(condition->root_instruction(), compare)); } { // Add the new variable to the while loop body. HloComputation* body = while_hlo->while_body(); TF_RETURN_IF_ERROR(change_op_shape(body->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(body->parameter_instruction(0)).status()); HloInstruction* old_root = body->root_instruction(); Shape shape = initialization->shape(); HloInstruction* induction_variable = body->AddInstruction(HloInstruction::CreateGetTupleElement( shape, body->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* increment = body->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(1))); induction_variable = body->AddInstruction(HloInstruction::CreateBinary( shape, HloOpcode::kAdd, induction_variable, increment)); HloInstruction* new_root = TupleUtil::AppendSuffix(old_root, {induction_variable}); body->set_root_instruction(new_root, /*accept_different_shape=*/true); } // Snapshot the users of while hlo before we add new users. std::vector<HloInstruction*> while_users(while_hlo->users().begin(), while_hlo->users().end()); // Take care of the users of this while loop. TF_RETURN_IF_ERROR(change_op_shape(while_hlo)); TF_ASSIGN_OR_RETURN(HloInstruction * prefix, replace_non_gte_users(while_hlo)); // If the while loop had been the root of its computation, make the prefix new // root. if (while_hlo->parent()->root_instruction() == while_hlo) { // We need to set accept_different_shape=true to reset the root shape to the // original, because we have already changed the shape of the old root // (while). if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix(while_hlo, new_tuple_size - 1); } while_hlo->parent()->set_root_instruction(prefix, /*accept_different_shape=*/true); } return absl::OkStatus(); } auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); VLOG(1) << "loop_bound = " << loop_bound; absl::Status HloControlFlowFlattening::RemoveInfeed( HloInstruction* infeed_hlo) const { CHECK_EQ(infeed_hlo->opcode(), HloOpcode::kInfeed); HloComputation* computation = infeed_hlo->parent(); CHECK_EQ(infeed_hlo->shape().tuple_shapes_size(), 2); const Shape& infeed_shape = ShapeUtil::GetSubshape(infeed_hlo->shape(), {0}); HloInstruction* custom_call = computation->AddInstruction( HloInstruction::CreateCustomCall(infeed_shape, {}, kNopCustomCallTarget)); // Create a new tuple consisting of the constant and the token that was // originally the operand of infeed, and replace the infeed operation. auto new_tuple = HloInstruction::CreateTuple( {custom_call, infeed_hlo->mutable_operand(0)}); TF_RETURN_IF_ERROR( computation->ReplaceWithNewInstruction(infeed_hlo, std::move(new_tuple))); custom_call->SetAndSanitizeName(infeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveRecvAndRecvDone( HloInstruction* recv_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(recv_done->opcode(), HloOpcode::kRecvDone); CHECK_EQ(recv_done->operand_count(), 1); HloInstruction* recv = recv_done->mutable_operand(0); CHECK_EQ(recv->opcode(), HloOpcode::kRecv); HloComputation* computation = recv_done->parent(); CHECK_EQ(recv_done->shape().tuple_shapes_size(), 2); HloModule* module = computation->parent(); HloInstruction* custom_call_recv = computation->AddInstruction(HloInstruction::CreateCustomCall( recv->shape(), recv->operands(), kNopCustomCallTarget)); std::string original_recv_name(recv->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv, custom_call_recv); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(recv, custom_call_recv)); custom_call_recv->SetAndSanitizeName(original_recv_name); std::string original_recv_done_name(recv_done->name()); HloInstruction* custom_call_recv_done = computation->AddInstruction( HloInstruction::CreateCustomCall( recv_done->shape(), recv_done->operands(), kNopCustomCallTarget), recv_done->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv_done, custom_call_recv_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(recv_done, custom_call_recv_done)); custom_call_recv_done->SetAndSanitizeName(original_recv_done_name); return std::make_pair(custom_call_recv, custom_call_recv_done); } absl::Status HloControlFlowFlattening::RemoveOutfeed( HloInstruction* outfeed_hlo) const { CHECK_EQ(outfeed_hlo->opcode(), HloOpcode::kOutfeed); HloComputation* computation = outfeed_hlo->parent(); // Replace the outfeed with a no-op custom call with side effect to ensure the // operands aren't DCE'd. HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( outfeed_hlo->shape(), outfeed_hlo->operands(), kNopReturnTokenCustomCallTarget)); Cast<HloCustomCallInstruction>(custom_call) ->set_custom_call_has_side_effect(true); // For SPMD graphs, partitioner requires that side-effecting custom calls have // a sharding that is non-replicated. custom_call->set_sharding(HloSharding::Manual()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(outfeed_hlo, custom_call)); custom_call->SetAndSanitizeName(outfeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveSendAndSendDone( HloInstruction* send_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(send_done->opcode(), HloOpcode::kSendDone); CHECK_EQ(send_done->operand_count(), 1); HloInstruction* send = send_done->mutable_operand(0); CHECK_EQ(send->opcode(), HloOpcode::kSend); HloComputation* computation = send_done->parent(); HloModule* module = computation->parent(); HloInstruction* custom_call_send = computation->AddInstruction(HloInstruction::CreateCustomCall( send->shape(), send->operands(), kNopCustomCallTarget)); std::string original_send_name(send->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send, custom_call_send); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(send, custom_call_send)); custom_call_send->SetAndSanitizeName(original_send_name); HloInstruction* custom_call_send_done = computation->AddInstruction(HloInstruction::CreateCustomCall( send_done->shape(), send_done->operands(), kNopReturnTokenCustomCallTarget)); std::string original_send_done_name(send_done->name()); Cast<HloCustomCallInstruction>(custom_call_send_done) ->set_custom_call_has_side_effect(true); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send_done, custom_call_send_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(send_done, custom_call_send_done)); custom_call_send_done->SetAndSanitizeName(original_send_done_name); return std::make_pair(custom_call_send, custom_call_send_done); } absl::StatusOr<HloInstruction*> HloControlFlowFlattening::RemoveCollective( HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( hlo->shape(), hlo->operands(), kNopCustomCallTarget)); // Copy backend config. This is necessary for a collective op in megacore // fusion. custom_call->CopyBackendConfigFrom(hlo); HloModule* module = computation->parent(); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, hlo, custom_call); } std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, custom_call)); custom_call->SetAndSanitizeName(original_op_name); return custom_call; } absl::Status HloControlFlowFlattening::RemoveId(HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* zero = CreateConstant(hlo->shape(), computation); std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, zero)); zero->SetAndSanitizeName(original_op_name); return absl::OkStatus(); } absl::StatusOr<bool> HloControlFlowFlattening::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { auto call_graph = CallGraph::Build(module); bool changed = false; absl::flat_hash_set<HloInstruction*> removed; for (HloComputation* computation : module->computations(execution_threads)) { // Do not change computations that are wrapped by async calls. Instead we // remove the async callers if needed. if (computation->IsAsyncComputation()) { continue; } for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (removed.contains(instruction)) { // Skip the instruction if it is already removed. continue; } if (flatten_while_loop_ && instruction->opcode() == HloOpcode::kWhile) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(FlattenWhileLoop(instruction, *call_graph)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kInfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveInfeed(instruction)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kOutfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveOutfeed(instruction)); changed = true; } else if (instruction->opcode() == HloOpcode::kSendDone) { auto send_done_instruction = DynCast<HloSendDoneInstruction>(instruction); CHECK(send_done_instruction); if (remove_comm_ || (remove_host_transfer_ && send_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveSendAndSendDone(instruction, &removed).status()); changed = true; } } else if (instruction->opcode() == HloOpcode::kRecvDone) { auto recv_done_instruction = DynCast<HloRecvDoneInstruction>(instruction); CHECK(recv_done_instruction); if (remove_comm_ || (remove_host_transfer_ && recv_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveRecvAndRecvDone(instruction, &removed).status()); changed = true; } } else if (remove_comm_ && IsCollective(instruction) && !instruction->parent()->IsFusionComputation() && (instruction->opcode() != HloOpcode::kAsyncStart && instruction->opcode() != HloOpcode::kAsyncUpdate)) { // We do not remove kAsyncStart or kAsyncUpdate here since we expect // them to be removed as a part of the async chain above. // We should remove the async chain all together because the async // wrapped computation is only associated with the AsyncStart. So we // need to refer to the AsyncStart in order to determine whether // the Done or the Update wraps a collective. if (instruction->opcode() == HloOpcode::kAsyncDone) { while (instruction->opcode() == HloOpcode::kAsyncDone || instruction->opcode() == HloOpcode::kAsyncUpdate || instruction->opcode() == HloOpcode::kAsyncStart) { HloInstruction* operand = instruction->mutable_operand(0); VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); instruction = operand; } } else { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); } changed = true; } else if (remove_comm_ && (instruction->opcode() == HloOpcode::kPartitionId || instruction->opcode() == HloOpcode::kReplicaId || (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == "SliceId"))) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveId(instruction)); changed = true; } } } HloDCE hlo_dce; TF_ASSIGN_OR_RETURN(bool dce_changed, hlo_dce.Run(module, execution_threads)); changed |= dce_changed; // Fix the schedule if the module was scheduled. if (changed && module->has_schedule()) { TF_RETURN_IF_ERROR(module->schedule().Update()); } XLA_VLOG_LINES(3, module->ToString()); return changed; } VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); XLA_VLOG_LINES(3, module->ToString());
#include "xla/tools/hlo_control_flow_flattening.h" #include <memory> #include <utility> #include "absl/strings/str_replace.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/collective_ops_utils.h" #include "xla/service/despecializer.h" #include "xla/service/hlo_verifier.h" #include "xla/service/spmd/spmd_partitioner.h" #include "xla/tests/hlo_test_base.h" #include "tsl/lib/core/status_test_util.h" class HloControlFlowFlatteningTest : public HloTestBase { public: absl::StatusOr<std::unique_ptr<HloModule>> PartitionComputation( std::unique_ptr<VerifiedHloModule> hlo_module, int64_t num_devices = 2) { spmd::SpmdPartitionerOptions options; auto collective_ops_creator = spmd::GetDefaultCollectiveOpsCreator(num_devices, /*num_replicas=*/1); collective_ops_creator.create_cross_partition_all_gather = nullptr; HloModuleConfig config = GetModuleConfigForTest(); config.set_use_spmd_partitioning(true); config.set_num_partitions(num_devices); HloPassPipeline pass("spmd-partitioning"); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); pass.AddPass<spmd::SpmdPartitioner>(num_devices, /*num_replicas=*/1, options, collective_ops_creator); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); TF_RETURN_IF_ERROR(pass.Run(hlo_module.get()).status()); return absl::StatusOr<std::unique_ptr<HloModule>>(std::move(hlo_module)); } }; TEST_F(HloControlFlowFlatteningTest, AllReduce) { absl::string_view hlo_string = R"( HloModule AllReduce sum { p0 = f32[] parameter(0) p1 = f32[] parameter(1) ROOT add = f32[] add(p0, p1) } ENTRY AllReduce { param0 = f32[3]{0} parameter(0) param1 = f32[12,5]{0,1} parameter(1) ROOT all-reduce = (bf16[3]{0}, bf16[12,5]{0,1}) all-reduce(param0, param1), to_apply=sum, replica_groups={} } )"; TF_ASSERT_OK_AND_ASSIGN(auto module, ParseAndReturnVerifiedModule(hlo_string)); HloControlFlowFlattening flattening( HloControlFlowFlattening::Options{/*while_execution_count=*/3}); EXPECT_TRUE(flattening.Run(module.get()).value()); TF_ASSERT_OK(HloVerifier(/*layout_sensitive=*/true, /*allow_mixed_precision=*/true) .Run(module.get()) .status()); EXPECT_THAT(module->entry_computation()->root_instruction(), op::CustomCall(op::Parameter(0), op::Parameter(1))); EXPECT_EQ(module->entry_computation()->root_instruction()->name(), "all-reduce"); }
HloControlFlowFlatteningTest_AllReduceStartAndDone
xla/tools/hlo_control_flow_flattening_test.cc
HloInstruction* CreateConstant(const Shape& shape, HloComputation* computation) { if (shape.IsTuple()) { std::vector<HloInstruction*> tuple_arguments(shape.tuple_shapes_size()); for (int index = 0; index < shape.tuple_shapes_size(); ++index) { tuple_arguments[index] = CreateConstant(shape.tuple_shapes(index), computation); } return computation->AddInstruction( HloInstruction::CreateTuple(tuple_arguments)); } else { return computation->AddInstruction( HloInstruction::CreateConstant(Literal::CreateFromShape(shape))); } } void PrintSubexpression(HloInstruction* inst, int depth) { if (depth == 0) { return; } for (auto* operand : inst->operands()) { PrintSubexpression(operand, depth - 1); } VLOG(2) << inst->ToString(); } VLOG(2) << inst->ToString(); bool IsConstantScalarInt(const HloInstruction* inst) { return inst->opcode() == HloOpcode::kConstant && ShapeUtil::IsEffectiveScalar(inst->shape()) && inst->shape().IsInteger(); } bool IsNotContainedInLoop(const HloInstruction& while_hlo, const CallGraph& call_graph) { const HloComputation* computation = while_hlo.parent(); while (!computation->IsEntryComputation()) { auto& node = call_graph.GetNode(computation); CHECK_EQ(node.caller_callsites().size(), 1) << "The module is not flattened!"; auto& callsite = node.caller_callsites()[0]; if (callsite.instruction()->opcode() == HloOpcode::kWhile) { // Another while loop has been found traversing up the call tree. return false; } computation = callsite.instruction()->parent(); } // No calling while loops were found. return true; } int GetLoopBound(const HloInstruction& while_hlo, const int default_loop_count, const int max_loop_count) { HloInstruction* condition = while_hlo.while_condition()->root_instruction(); if (condition->opcode() == HloOpcode::kCompare) { int64_t value = 0; Comparison::Direction cmp = condition->comparison_direction(); if ((cmp == Comparison::Direction::kLt || cmp == Comparison::Direction::kLe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(1))) { value = *condition->operand(1)->literal().GetFirstInteger(); } else if ((cmp == Comparison::Direction::kGt || cmp == Comparison::Direction::kGe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(0))) { value = *condition->operand(0)->literal().GetFirstInteger(); } if (value > 0) { // Caps to a max loop count to avoid long execution times. return std::min(value, static_cast<int64_t>(max_loop_count)); } } return default_loop_count; } int GetLoopBoundWithOuterLoopMax(const HloInstruction& while_hlo, const CallGraph& call_graph, const int default_loop_count, const int max_outer_loop_count, const int max_loop_count) { int loop_bound = GetLoopBound(while_hlo, default_loop_count, max_loop_count); if (loop_bound > max_outer_loop_count) { // First does the inexpensive loop bound check to avoid as many // expensive graph traversals in IsNotContainedInLoop as possible. if (IsNotContainedInLoop(while_hlo, call_graph)) { return max_outer_loop_count; } } return loop_bound; } absl::Status HloControlFlowFlattening::FlattenWhileLoop( HloInstruction* while_hlo, const CallGraph& call_graph) const { CHECK_EQ(while_hlo->opcode(), HloOpcode::kWhile); HloComputation* computation = while_hlo->parent(); // Add a new induction variable. HloInstruction* initialization = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(0))); // Create a new while operand with the induction variable added. HloInstruction* old_tuple = while_hlo->mutable_operand(0); HloInstruction* new_tuple = TupleUtil::AppendSuffix(old_tuple, {initialization}); int new_tuple_size = new_tuple->shape().tuple_shapes().size(); TF_RETURN_IF_ERROR(while_hlo->ReplaceOperandWithDifferentShape(0, new_tuple)); auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; // Replace the given tuple-shaped instruction of size N in each of its // non-get-tuple-element users with a new tuple instruction which has the // first N - 1 elements. auto replace_non_gte_users = [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; { // Add the new variable to the while loop condition. HloComputation* condition = while_hlo->while_condition(); TF_RETURN_IF_ERROR(change_op_shape(condition->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(condition->parameter_instruction(0)).status()); if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); PrintSubexpression(condition->root_instruction(), /*depth=*/3); } const int loop_bound = GetLoopBoundWithOuterLoopMax( *while_hlo, call_graph, while_execution_count_, max_outer_loop_count_, max_loop_count_); VLOG(1) << "loop_bound = " << loop_bound; HloInstruction* limit = condition->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(loop_bound))); Shape shape = initialization->shape(); HloInstruction* induction_variable = condition->AddInstruction(HloInstruction::CreateGetTupleElement( shape, condition->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* compare = condition->AddInstruction(HloInstruction::CreateCompare( ShapeUtil::MakeShape(PRED, {}), induction_variable, limit, ComparisonDirection::kLt)); TF_RETURN_IF_ERROR( condition->ReplaceInstruction(condition->root_instruction(), compare)); } { // Add the new variable to the while loop body. HloComputation* body = while_hlo->while_body(); TF_RETURN_IF_ERROR(change_op_shape(body->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(body->parameter_instruction(0)).status()); HloInstruction* old_root = body->root_instruction(); Shape shape = initialization->shape(); HloInstruction* induction_variable = body->AddInstruction(HloInstruction::CreateGetTupleElement( shape, body->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* increment = body->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(1))); induction_variable = body->AddInstruction(HloInstruction::CreateBinary( shape, HloOpcode::kAdd, induction_variable, increment)); HloInstruction* new_root = TupleUtil::AppendSuffix(old_root, {induction_variable}); body->set_root_instruction(new_root, /*accept_different_shape=*/true); } // Snapshot the users of while hlo before we add new users. std::vector<HloInstruction*> while_users(while_hlo->users().begin(), while_hlo->users().end()); // Take care of the users of this while loop. TF_RETURN_IF_ERROR(change_op_shape(while_hlo)); TF_ASSIGN_OR_RETURN(HloInstruction * prefix, replace_non_gte_users(while_hlo)); // If the while loop had been the root of its computation, make the prefix new // root. if (while_hlo->parent()->root_instruction() == while_hlo) { // We need to set accept_different_shape=true to reset the root shape to the // original, because we have already changed the shape of the old root // (while). if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix(while_hlo, new_tuple_size - 1); } while_hlo->parent()->set_root_instruction(prefix, /*accept_different_shape=*/true); } return absl::OkStatus(); } auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); VLOG(1) << "loop_bound = " << loop_bound; absl::Status HloControlFlowFlattening::RemoveInfeed( HloInstruction* infeed_hlo) const { CHECK_EQ(infeed_hlo->opcode(), HloOpcode::kInfeed); HloComputation* computation = infeed_hlo->parent(); CHECK_EQ(infeed_hlo->shape().tuple_shapes_size(), 2); const Shape& infeed_shape = ShapeUtil::GetSubshape(infeed_hlo->shape(), {0}); HloInstruction* custom_call = computation->AddInstruction( HloInstruction::CreateCustomCall(infeed_shape, {}, kNopCustomCallTarget)); // Create a new tuple consisting of the constant and the token that was // originally the operand of infeed, and replace the infeed operation. auto new_tuple = HloInstruction::CreateTuple( {custom_call, infeed_hlo->mutable_operand(0)}); TF_RETURN_IF_ERROR( computation->ReplaceWithNewInstruction(infeed_hlo, std::move(new_tuple))); custom_call->SetAndSanitizeName(infeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveRecvAndRecvDone( HloInstruction* recv_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(recv_done->opcode(), HloOpcode::kRecvDone); CHECK_EQ(recv_done->operand_count(), 1); HloInstruction* recv = recv_done->mutable_operand(0); CHECK_EQ(recv->opcode(), HloOpcode::kRecv); HloComputation* computation = recv_done->parent(); CHECK_EQ(recv_done->shape().tuple_shapes_size(), 2); HloModule* module = computation->parent(); HloInstruction* custom_call_recv = computation->AddInstruction(HloInstruction::CreateCustomCall( recv->shape(), recv->operands(), kNopCustomCallTarget)); std::string original_recv_name(recv->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv, custom_call_recv); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(recv, custom_call_recv)); custom_call_recv->SetAndSanitizeName(original_recv_name); std::string original_recv_done_name(recv_done->name()); HloInstruction* custom_call_recv_done = computation->AddInstruction( HloInstruction::CreateCustomCall( recv_done->shape(), recv_done->operands(), kNopCustomCallTarget), recv_done->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv_done, custom_call_recv_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(recv_done, custom_call_recv_done)); custom_call_recv_done->SetAndSanitizeName(original_recv_done_name); return std::make_pair(custom_call_recv, custom_call_recv_done); } absl::Status HloControlFlowFlattening::RemoveOutfeed( HloInstruction* outfeed_hlo) const { CHECK_EQ(outfeed_hlo->opcode(), HloOpcode::kOutfeed); HloComputation* computation = outfeed_hlo->parent(); // Replace the outfeed with a no-op custom call with side effect to ensure the // operands aren't DCE'd. HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( outfeed_hlo->shape(), outfeed_hlo->operands(), kNopReturnTokenCustomCallTarget)); Cast<HloCustomCallInstruction>(custom_call) ->set_custom_call_has_side_effect(true); // For SPMD graphs, partitioner requires that side-effecting custom calls have // a sharding that is non-replicated. custom_call->set_sharding(HloSharding::Manual()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(outfeed_hlo, custom_call)); custom_call->SetAndSanitizeName(outfeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveSendAndSendDone( HloInstruction* send_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(send_done->opcode(), HloOpcode::kSendDone); CHECK_EQ(send_done->operand_count(), 1); HloInstruction* send = send_done->mutable_operand(0); CHECK_EQ(send->opcode(), HloOpcode::kSend); HloComputation* computation = send_done->parent(); HloModule* module = computation->parent(); HloInstruction* custom_call_send = computation->AddInstruction(HloInstruction::CreateCustomCall( send->shape(), send->operands(), kNopCustomCallTarget)); std::string original_send_name(send->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send, custom_call_send); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(send, custom_call_send)); custom_call_send->SetAndSanitizeName(original_send_name); HloInstruction* custom_call_send_done = computation->AddInstruction(HloInstruction::CreateCustomCall( send_done->shape(), send_done->operands(), kNopReturnTokenCustomCallTarget)); std::string original_send_done_name(send_done->name()); Cast<HloCustomCallInstruction>(custom_call_send_done) ->set_custom_call_has_side_effect(true); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send_done, custom_call_send_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(send_done, custom_call_send_done)); custom_call_send_done->SetAndSanitizeName(original_send_done_name); return std::make_pair(custom_call_send, custom_call_send_done); } absl::StatusOr<HloInstruction*> HloControlFlowFlattening::RemoveCollective( HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( hlo->shape(), hlo->operands(), kNopCustomCallTarget)); // Copy backend config. This is necessary for a collective op in megacore // fusion. custom_call->CopyBackendConfigFrom(hlo); HloModule* module = computation->parent(); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, hlo, custom_call); } std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, custom_call)); custom_call->SetAndSanitizeName(original_op_name); return custom_call; } absl::Status HloControlFlowFlattening::RemoveId(HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* zero = CreateConstant(hlo->shape(), computation); std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, zero)); zero->SetAndSanitizeName(original_op_name); return absl::OkStatus(); } absl::StatusOr<bool> HloControlFlowFlattening::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { auto call_graph = CallGraph::Build(module); bool changed = false; absl::flat_hash_set<HloInstruction*> removed; for (HloComputation* computation : module->computations(execution_threads)) { // Do not change computations that are wrapped by async calls. Instead we // remove the async callers if needed. if (computation->IsAsyncComputation()) { continue; } for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (removed.contains(instruction)) { // Skip the instruction if it is already removed. continue; } if (flatten_while_loop_ && instruction->opcode() == HloOpcode::kWhile) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(FlattenWhileLoop(instruction, *call_graph)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kInfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveInfeed(instruction)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kOutfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveOutfeed(instruction)); changed = true; } else if (instruction->opcode() == HloOpcode::kSendDone) { auto send_done_instruction = DynCast<HloSendDoneInstruction>(instruction); CHECK(send_done_instruction); if (remove_comm_ || (remove_host_transfer_ && send_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveSendAndSendDone(instruction, &removed).status()); changed = true; } } else if (instruction->opcode() == HloOpcode::kRecvDone) { auto recv_done_instruction = DynCast<HloRecvDoneInstruction>(instruction); CHECK(recv_done_instruction); if (remove_comm_ || (remove_host_transfer_ && recv_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveRecvAndRecvDone(instruction, &removed).status()); changed = true; } } else if (remove_comm_ && IsCollective(instruction) && !instruction->parent()->IsFusionComputation() && (instruction->opcode() != HloOpcode::kAsyncStart && instruction->opcode() != HloOpcode::kAsyncUpdate)) { // We do not remove kAsyncStart or kAsyncUpdate here since we expect // them to be removed as a part of the async chain above. // We should remove the async chain all together because the async // wrapped computation is only associated with the AsyncStart. So we // need to refer to the AsyncStart in order to determine whether // the Done or the Update wraps a collective. if (instruction->opcode() == HloOpcode::kAsyncDone) { while (instruction->opcode() == HloOpcode::kAsyncDone || instruction->opcode() == HloOpcode::kAsyncUpdate || instruction->opcode() == HloOpcode::kAsyncStart) { HloInstruction* operand = instruction->mutable_operand(0); VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); instruction = operand; } } else { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); } changed = true; } else if (remove_comm_ && (instruction->opcode() == HloOpcode::kPartitionId || instruction->opcode() == HloOpcode::kReplicaId || (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == "SliceId"))) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveId(instruction)); changed = true; } } } HloDCE hlo_dce; TF_ASSIGN_OR_RETURN(bool dce_changed, hlo_dce.Run(module, execution_threads)); changed |= dce_changed; // Fix the schedule if the module was scheduled. if (changed && module->has_schedule()) { TF_RETURN_IF_ERROR(module->schedule().Update()); } XLA_VLOG_LINES(3, module->ToString()); return changed; } VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); XLA_VLOG_LINES(3, module->ToString());
#include "xla/tools/hlo_control_flow_flattening.h" #include <memory> #include <utility> #include "absl/strings/str_replace.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/collective_ops_utils.h" #include "xla/service/despecializer.h" #include "xla/service/hlo_verifier.h" #include "xla/service/spmd/spmd_partitioner.h" #include "xla/tests/hlo_test_base.h" #include "tsl/lib/core/status_test_util.h" class HloControlFlowFlatteningTest : public HloTestBase { public: absl::StatusOr<std::unique_ptr<HloModule>> PartitionComputation( std::unique_ptr<VerifiedHloModule> hlo_module, int64_t num_devices = 2) { spmd::SpmdPartitionerOptions options; auto collective_ops_creator = spmd::GetDefaultCollectiveOpsCreator(num_devices, /*num_replicas=*/1); collective_ops_creator.create_cross_partition_all_gather = nullptr; HloModuleConfig config = GetModuleConfigForTest(); config.set_use_spmd_partitioning(true); config.set_num_partitions(num_devices); HloPassPipeline pass("spmd-partitioning"); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); pass.AddPass<spmd::SpmdPartitioner>(num_devices, /*num_replicas=*/1, options, collective_ops_creator); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); TF_RETURN_IF_ERROR(pass.Run(hlo_module.get()).status()); return absl::StatusOr<std::unique_ptr<HloModule>>(std::move(hlo_module)); } }; TEST_F(HloControlFlowFlatteningTest, AllReduceStartAndDone) { absl::string_view hlo_string = R"( HloModule CRS add { lhs = f32[] parameter(0) rhs = f32[] parameter(1) ROOT add = f32[] add(lhs, rhs) } ENTRY CRS { input = f32[8]{0} parameter(0) crs = f32[8]{0} all-reduce-start(input), replica_groups={}, to_apply=add ROOT done = f32[8]{0} all-reduce-done(crs) } )"; TF_ASSERT_OK_AND_ASSIGN(auto module, ParseAndReturnVerifiedModule(hlo_string)); HloControlFlowFlattening flattening( HloControlFlowFlattening::Options{/*while_execution_count=*/3}); EXPECT_TRUE(flattening.Run(module.get()).value()); TF_ASSERT_OK(HloVerifier(/*layout_sensitive=*/true, /*allow_mixed_precision=*/true) .Run(module.get()) .status()); EXPECT_THAT(module->entry_computation()->root_instruction(), op::CustomCall(op::CustomCall(op::Parameter(0)))); EXPECT_EQ(module->entry_computation()->root_instruction()->name(), "done"); EXPECT_EQ(module->entry_computation()->root_instruction()->operand(0)->name(), "crs"); }
HloControlFlowFlatteningTest_AllToAll
xla/tools/hlo_control_flow_flattening_test.cc
HloInstruction* CreateConstant(const Shape& shape, HloComputation* computation) { if (shape.IsTuple()) { std::vector<HloInstruction*> tuple_arguments(shape.tuple_shapes_size()); for (int index = 0; index < shape.tuple_shapes_size(); ++index) { tuple_arguments[index] = CreateConstant(shape.tuple_shapes(index), computation); } return computation->AddInstruction( HloInstruction::CreateTuple(tuple_arguments)); } else { return computation->AddInstruction( HloInstruction::CreateConstant(Literal::CreateFromShape(shape))); } } void PrintSubexpression(HloInstruction* inst, int depth) { if (depth == 0) { return; } for (auto* operand : inst->operands()) { PrintSubexpression(operand, depth - 1); } VLOG(2) << inst->ToString(); } VLOG(2) << inst->ToString(); bool IsConstantScalarInt(const HloInstruction* inst) { return inst->opcode() == HloOpcode::kConstant && ShapeUtil::IsEffectiveScalar(inst->shape()) && inst->shape().IsInteger(); } bool IsNotContainedInLoop(const HloInstruction& while_hlo, const CallGraph& call_graph) { const HloComputation* computation = while_hlo.parent(); while (!computation->IsEntryComputation()) { auto& node = call_graph.GetNode(computation); CHECK_EQ(node.caller_callsites().size(), 1) << "The module is not flattened!"; auto& callsite = node.caller_callsites()[0]; if (callsite.instruction()->opcode() == HloOpcode::kWhile) { // Another while loop has been found traversing up the call tree. return false; } computation = callsite.instruction()->parent(); } // No calling while loops were found. return true; } int GetLoopBound(const HloInstruction& while_hlo, const int default_loop_count, const int max_loop_count) { HloInstruction* condition = while_hlo.while_condition()->root_instruction(); if (condition->opcode() == HloOpcode::kCompare) { int64_t value = 0; Comparison::Direction cmp = condition->comparison_direction(); if ((cmp == Comparison::Direction::kLt || cmp == Comparison::Direction::kLe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(1))) { value = *condition->operand(1)->literal().GetFirstInteger(); } else if ((cmp == Comparison::Direction::kGt || cmp == Comparison::Direction::kGe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(0))) { value = *condition->operand(0)->literal().GetFirstInteger(); } if (value > 0) { // Caps to a max loop count to avoid long execution times. return std::min(value, static_cast<int64_t>(max_loop_count)); } } return default_loop_count; } int GetLoopBoundWithOuterLoopMax(const HloInstruction& while_hlo, const CallGraph& call_graph, const int default_loop_count, const int max_outer_loop_count, const int max_loop_count) { int loop_bound = GetLoopBound(while_hlo, default_loop_count, max_loop_count); if (loop_bound > max_outer_loop_count) { // First does the inexpensive loop bound check to avoid as many // expensive graph traversals in IsNotContainedInLoop as possible. if (IsNotContainedInLoop(while_hlo, call_graph)) { return max_outer_loop_count; } } return loop_bound; } absl::Status HloControlFlowFlattening::FlattenWhileLoop( HloInstruction* while_hlo, const CallGraph& call_graph) const { CHECK_EQ(while_hlo->opcode(), HloOpcode::kWhile); HloComputation* computation = while_hlo->parent(); // Add a new induction variable. HloInstruction* initialization = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(0))); // Create a new while operand with the induction variable added. HloInstruction* old_tuple = while_hlo->mutable_operand(0); HloInstruction* new_tuple = TupleUtil::AppendSuffix(old_tuple, {initialization}); int new_tuple_size = new_tuple->shape().tuple_shapes().size(); TF_RETURN_IF_ERROR(while_hlo->ReplaceOperandWithDifferentShape(0, new_tuple)); auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; // Replace the given tuple-shaped instruction of size N in each of its // non-get-tuple-element users with a new tuple instruction which has the // first N - 1 elements. auto replace_non_gte_users = [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; { // Add the new variable to the while loop condition. HloComputation* condition = while_hlo->while_condition(); TF_RETURN_IF_ERROR(change_op_shape(condition->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(condition->parameter_instruction(0)).status()); if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); PrintSubexpression(condition->root_instruction(), /*depth=*/3); } const int loop_bound = GetLoopBoundWithOuterLoopMax( *while_hlo, call_graph, while_execution_count_, max_outer_loop_count_, max_loop_count_); VLOG(1) << "loop_bound = " << loop_bound; HloInstruction* limit = condition->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(loop_bound))); Shape shape = initialization->shape(); HloInstruction* induction_variable = condition->AddInstruction(HloInstruction::CreateGetTupleElement( shape, condition->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* compare = condition->AddInstruction(HloInstruction::CreateCompare( ShapeUtil::MakeShape(PRED, {}), induction_variable, limit, ComparisonDirection::kLt)); TF_RETURN_IF_ERROR( condition->ReplaceInstruction(condition->root_instruction(), compare)); } { // Add the new variable to the while loop body. HloComputation* body = while_hlo->while_body(); TF_RETURN_IF_ERROR(change_op_shape(body->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(body->parameter_instruction(0)).status()); HloInstruction* old_root = body->root_instruction(); Shape shape = initialization->shape(); HloInstruction* induction_variable = body->AddInstruction(HloInstruction::CreateGetTupleElement( shape, body->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* increment = body->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(1))); induction_variable = body->AddInstruction(HloInstruction::CreateBinary( shape, HloOpcode::kAdd, induction_variable, increment)); HloInstruction* new_root = TupleUtil::AppendSuffix(old_root, {induction_variable}); body->set_root_instruction(new_root, /*accept_different_shape=*/true); } // Snapshot the users of while hlo before we add new users. std::vector<HloInstruction*> while_users(while_hlo->users().begin(), while_hlo->users().end()); // Take care of the users of this while loop. TF_RETURN_IF_ERROR(change_op_shape(while_hlo)); TF_ASSIGN_OR_RETURN(HloInstruction * prefix, replace_non_gte_users(while_hlo)); // If the while loop had been the root of its computation, make the prefix new // root. if (while_hlo->parent()->root_instruction() == while_hlo) { // We need to set accept_different_shape=true to reset the root shape to the // original, because we have already changed the shape of the old root // (while). if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix(while_hlo, new_tuple_size - 1); } while_hlo->parent()->set_root_instruction(prefix, /*accept_different_shape=*/true); } return absl::OkStatus(); } auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); VLOG(1) << "loop_bound = " << loop_bound; absl::Status HloControlFlowFlattening::RemoveInfeed( HloInstruction* infeed_hlo) const { CHECK_EQ(infeed_hlo->opcode(), HloOpcode::kInfeed); HloComputation* computation = infeed_hlo->parent(); CHECK_EQ(infeed_hlo->shape().tuple_shapes_size(), 2); const Shape& infeed_shape = ShapeUtil::GetSubshape(infeed_hlo->shape(), {0}); HloInstruction* custom_call = computation->AddInstruction( HloInstruction::CreateCustomCall(infeed_shape, {}, kNopCustomCallTarget)); // Create a new tuple consisting of the constant and the token that was // originally the operand of infeed, and replace the infeed operation. auto new_tuple = HloInstruction::CreateTuple( {custom_call, infeed_hlo->mutable_operand(0)}); TF_RETURN_IF_ERROR( computation->ReplaceWithNewInstruction(infeed_hlo, std::move(new_tuple))); custom_call->SetAndSanitizeName(infeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveRecvAndRecvDone( HloInstruction* recv_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(recv_done->opcode(), HloOpcode::kRecvDone); CHECK_EQ(recv_done->operand_count(), 1); HloInstruction* recv = recv_done->mutable_operand(0); CHECK_EQ(recv->opcode(), HloOpcode::kRecv); HloComputation* computation = recv_done->parent(); CHECK_EQ(recv_done->shape().tuple_shapes_size(), 2); HloModule* module = computation->parent(); HloInstruction* custom_call_recv = computation->AddInstruction(HloInstruction::CreateCustomCall( recv->shape(), recv->operands(), kNopCustomCallTarget)); std::string original_recv_name(recv->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv, custom_call_recv); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(recv, custom_call_recv)); custom_call_recv->SetAndSanitizeName(original_recv_name); std::string original_recv_done_name(recv_done->name()); HloInstruction* custom_call_recv_done = computation->AddInstruction( HloInstruction::CreateCustomCall( recv_done->shape(), recv_done->operands(), kNopCustomCallTarget), recv_done->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv_done, custom_call_recv_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(recv_done, custom_call_recv_done)); custom_call_recv_done->SetAndSanitizeName(original_recv_done_name); return std::make_pair(custom_call_recv, custom_call_recv_done); } absl::Status HloControlFlowFlattening::RemoveOutfeed( HloInstruction* outfeed_hlo) const { CHECK_EQ(outfeed_hlo->opcode(), HloOpcode::kOutfeed); HloComputation* computation = outfeed_hlo->parent(); // Replace the outfeed with a no-op custom call with side effect to ensure the // operands aren't DCE'd. HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( outfeed_hlo->shape(), outfeed_hlo->operands(), kNopReturnTokenCustomCallTarget)); Cast<HloCustomCallInstruction>(custom_call) ->set_custom_call_has_side_effect(true); // For SPMD graphs, partitioner requires that side-effecting custom calls have // a sharding that is non-replicated. custom_call->set_sharding(HloSharding::Manual()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(outfeed_hlo, custom_call)); custom_call->SetAndSanitizeName(outfeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveSendAndSendDone( HloInstruction* send_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(send_done->opcode(), HloOpcode::kSendDone); CHECK_EQ(send_done->operand_count(), 1); HloInstruction* send = send_done->mutable_operand(0); CHECK_EQ(send->opcode(), HloOpcode::kSend); HloComputation* computation = send_done->parent(); HloModule* module = computation->parent(); HloInstruction* custom_call_send = computation->AddInstruction(HloInstruction::CreateCustomCall( send->shape(), send->operands(), kNopCustomCallTarget)); std::string original_send_name(send->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send, custom_call_send); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(send, custom_call_send)); custom_call_send->SetAndSanitizeName(original_send_name); HloInstruction* custom_call_send_done = computation->AddInstruction(HloInstruction::CreateCustomCall( send_done->shape(), send_done->operands(), kNopReturnTokenCustomCallTarget)); std::string original_send_done_name(send_done->name()); Cast<HloCustomCallInstruction>(custom_call_send_done) ->set_custom_call_has_side_effect(true); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send_done, custom_call_send_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(send_done, custom_call_send_done)); custom_call_send_done->SetAndSanitizeName(original_send_done_name); return std::make_pair(custom_call_send, custom_call_send_done); } absl::StatusOr<HloInstruction*> HloControlFlowFlattening::RemoveCollective( HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( hlo->shape(), hlo->operands(), kNopCustomCallTarget)); // Copy backend config. This is necessary for a collective op in megacore // fusion. custom_call->CopyBackendConfigFrom(hlo); HloModule* module = computation->parent(); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, hlo, custom_call); } std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, custom_call)); custom_call->SetAndSanitizeName(original_op_name); return custom_call; } absl::Status HloControlFlowFlattening::RemoveId(HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* zero = CreateConstant(hlo->shape(), computation); std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, zero)); zero->SetAndSanitizeName(original_op_name); return absl::OkStatus(); } absl::StatusOr<bool> HloControlFlowFlattening::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { auto call_graph = CallGraph::Build(module); bool changed = false; absl::flat_hash_set<HloInstruction*> removed; for (HloComputation* computation : module->computations(execution_threads)) { // Do not change computations that are wrapped by async calls. Instead we // remove the async callers if needed. if (computation->IsAsyncComputation()) { continue; } for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (removed.contains(instruction)) { // Skip the instruction if it is already removed. continue; } if (flatten_while_loop_ && instruction->opcode() == HloOpcode::kWhile) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(FlattenWhileLoop(instruction, *call_graph)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kInfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveInfeed(instruction)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kOutfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveOutfeed(instruction)); changed = true; } else if (instruction->opcode() == HloOpcode::kSendDone) { auto send_done_instruction = DynCast<HloSendDoneInstruction>(instruction); CHECK(send_done_instruction); if (remove_comm_ || (remove_host_transfer_ && send_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveSendAndSendDone(instruction, &removed).status()); changed = true; } } else if (instruction->opcode() == HloOpcode::kRecvDone) { auto recv_done_instruction = DynCast<HloRecvDoneInstruction>(instruction); CHECK(recv_done_instruction); if (remove_comm_ || (remove_host_transfer_ && recv_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveRecvAndRecvDone(instruction, &removed).status()); changed = true; } } else if (remove_comm_ && IsCollective(instruction) && !instruction->parent()->IsFusionComputation() && (instruction->opcode() != HloOpcode::kAsyncStart && instruction->opcode() != HloOpcode::kAsyncUpdate)) { // We do not remove kAsyncStart or kAsyncUpdate here since we expect // them to be removed as a part of the async chain above. // We should remove the async chain all together because the async // wrapped computation is only associated with the AsyncStart. So we // need to refer to the AsyncStart in order to determine whether // the Done or the Update wraps a collective. if (instruction->opcode() == HloOpcode::kAsyncDone) { while (instruction->opcode() == HloOpcode::kAsyncDone || instruction->opcode() == HloOpcode::kAsyncUpdate || instruction->opcode() == HloOpcode::kAsyncStart) { HloInstruction* operand = instruction->mutable_operand(0); VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); instruction = operand; } } else { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); } changed = true; } else if (remove_comm_ && (instruction->opcode() == HloOpcode::kPartitionId || instruction->opcode() == HloOpcode::kReplicaId || (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == "SliceId"))) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveId(instruction)); changed = true; } } } HloDCE hlo_dce; TF_ASSIGN_OR_RETURN(bool dce_changed, hlo_dce.Run(module, execution_threads)); changed |= dce_changed; // Fix the schedule if the module was scheduled. if (changed && module->has_schedule()) { TF_RETURN_IF_ERROR(module->schedule().Update()); } XLA_VLOG_LINES(3, module->ToString()); return changed; } VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); XLA_VLOG_LINES(3, module->ToString());
#include "xla/tools/hlo_control_flow_flattening.h" #include <memory> #include <utility> #include "absl/strings/str_replace.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/collective_ops_utils.h" #include "xla/service/despecializer.h" #include "xla/service/hlo_verifier.h" #include "xla/service/spmd/spmd_partitioner.h" #include "xla/tests/hlo_test_base.h" #include "tsl/lib/core/status_test_util.h" class HloControlFlowFlatteningTest : public HloTestBase { public: absl::StatusOr<std::unique_ptr<HloModule>> PartitionComputation( std::unique_ptr<VerifiedHloModule> hlo_module, int64_t num_devices = 2) { spmd::SpmdPartitionerOptions options; auto collective_ops_creator = spmd::GetDefaultCollectiveOpsCreator(num_devices, /*num_replicas=*/1); collective_ops_creator.create_cross_partition_all_gather = nullptr; HloModuleConfig config = GetModuleConfigForTest(); config.set_use_spmd_partitioning(true); config.set_num_partitions(num_devices); HloPassPipeline pass("spmd-partitioning"); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); pass.AddPass<spmd::SpmdPartitioner>(num_devices, /*num_replicas=*/1, options, collective_ops_creator); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); TF_RETURN_IF_ERROR(pass.Run(hlo_module.get()).status()); return absl::StatusOr<std::unique_ptr<HloModule>>(std::move(hlo_module)); } }; TEST_F(HloControlFlowFlatteningTest, AllToAll) { absl::string_view hlo_string = R"( HloModule AllToAll ENTRY AllToAll { input = f32[128,32]{0,1} parameter(0) ROOT a2a = (f32[128,32]{0,1}) all-to-all(input), replica_groups={} } )"; TF_ASSERT_OK_AND_ASSIGN(auto module, ParseAndReturnVerifiedModule(hlo_string)); HloControlFlowFlattening flattening( HloControlFlowFlattening::Options{/*while_execution_count=*/3}); EXPECT_TRUE(flattening.Run(module.get()).value()); TF_ASSERT_OK(HloVerifier(/*layout_sensitive=*/true, /*allow_mixed_precision=*/true) .Run(module.get()) .status()); EXPECT_THAT(module->entry_computation()->root_instruction(), op::CustomCall(op::Parameter(0))); EXPECT_EQ(module->entry_computation()->root_instruction()->name(), "a2a"); }
HloControlFlowFlatteningTest_AsyncAllToAll
xla/tools/hlo_control_flow_flattening_test.cc
HloInstruction* CreateConstant(const Shape& shape, HloComputation* computation) { if (shape.IsTuple()) { std::vector<HloInstruction*> tuple_arguments(shape.tuple_shapes_size()); for (int index = 0; index < shape.tuple_shapes_size(); ++index) { tuple_arguments[index] = CreateConstant(shape.tuple_shapes(index), computation); } return computation->AddInstruction( HloInstruction::CreateTuple(tuple_arguments)); } else { return computation->AddInstruction( HloInstruction::CreateConstant(Literal::CreateFromShape(shape))); } } void PrintSubexpression(HloInstruction* inst, int depth) { if (depth == 0) { return; } for (auto* operand : inst->operands()) { PrintSubexpression(operand, depth - 1); } VLOG(2) << inst->ToString(); } VLOG(2) << inst->ToString(); bool IsConstantScalarInt(const HloInstruction* inst) { return inst->opcode() == HloOpcode::kConstant && ShapeUtil::IsEffectiveScalar(inst->shape()) && inst->shape().IsInteger(); } bool IsNotContainedInLoop(const HloInstruction& while_hlo, const CallGraph& call_graph) { const HloComputation* computation = while_hlo.parent(); while (!computation->IsEntryComputation()) { auto& node = call_graph.GetNode(computation); CHECK_EQ(node.caller_callsites().size(), 1) << "The module is not flattened!"; auto& callsite = node.caller_callsites()[0]; if (callsite.instruction()->opcode() == HloOpcode::kWhile) { // Another while loop has been found traversing up the call tree. return false; } computation = callsite.instruction()->parent(); } // No calling while loops were found. return true; } int GetLoopBound(const HloInstruction& while_hlo, const int default_loop_count, const int max_loop_count) { HloInstruction* condition = while_hlo.while_condition()->root_instruction(); if (condition->opcode() == HloOpcode::kCompare) { int64_t value = 0; Comparison::Direction cmp = condition->comparison_direction(); if ((cmp == Comparison::Direction::kLt || cmp == Comparison::Direction::kLe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(1))) { value = *condition->operand(1)->literal().GetFirstInteger(); } else if ((cmp == Comparison::Direction::kGt || cmp == Comparison::Direction::kGe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(0))) { value = *condition->operand(0)->literal().GetFirstInteger(); } if (value > 0) { // Caps to a max loop count to avoid long execution times. return std::min(value, static_cast<int64_t>(max_loop_count)); } } return default_loop_count; } int GetLoopBoundWithOuterLoopMax(const HloInstruction& while_hlo, const CallGraph& call_graph, const int default_loop_count, const int max_outer_loop_count, const int max_loop_count) { int loop_bound = GetLoopBound(while_hlo, default_loop_count, max_loop_count); if (loop_bound > max_outer_loop_count) { // First does the inexpensive loop bound check to avoid as many // expensive graph traversals in IsNotContainedInLoop as possible. if (IsNotContainedInLoop(while_hlo, call_graph)) { return max_outer_loop_count; } } return loop_bound; } absl::Status HloControlFlowFlattening::FlattenWhileLoop( HloInstruction* while_hlo, const CallGraph& call_graph) const { CHECK_EQ(while_hlo->opcode(), HloOpcode::kWhile); HloComputation* computation = while_hlo->parent(); // Add a new induction variable. HloInstruction* initialization = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(0))); // Create a new while operand with the induction variable added. HloInstruction* old_tuple = while_hlo->mutable_operand(0); HloInstruction* new_tuple = TupleUtil::AppendSuffix(old_tuple, {initialization}); int new_tuple_size = new_tuple->shape().tuple_shapes().size(); TF_RETURN_IF_ERROR(while_hlo->ReplaceOperandWithDifferentShape(0, new_tuple)); auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; // Replace the given tuple-shaped instruction of size N in each of its // non-get-tuple-element users with a new tuple instruction which has the // first N - 1 elements. auto replace_non_gte_users = [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; { // Add the new variable to the while loop condition. HloComputation* condition = while_hlo->while_condition(); TF_RETURN_IF_ERROR(change_op_shape(condition->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(condition->parameter_instruction(0)).status()); if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); PrintSubexpression(condition->root_instruction(), /*depth=*/3); } const int loop_bound = GetLoopBoundWithOuterLoopMax( *while_hlo, call_graph, while_execution_count_, max_outer_loop_count_, max_loop_count_); VLOG(1) << "loop_bound = " << loop_bound; HloInstruction* limit = condition->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(loop_bound))); Shape shape = initialization->shape(); HloInstruction* induction_variable = condition->AddInstruction(HloInstruction::CreateGetTupleElement( shape, condition->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* compare = condition->AddInstruction(HloInstruction::CreateCompare( ShapeUtil::MakeShape(PRED, {}), induction_variable, limit, ComparisonDirection::kLt)); TF_RETURN_IF_ERROR( condition->ReplaceInstruction(condition->root_instruction(), compare)); } { // Add the new variable to the while loop body. HloComputation* body = while_hlo->while_body(); TF_RETURN_IF_ERROR(change_op_shape(body->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(body->parameter_instruction(0)).status()); HloInstruction* old_root = body->root_instruction(); Shape shape = initialization->shape(); HloInstruction* induction_variable = body->AddInstruction(HloInstruction::CreateGetTupleElement( shape, body->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* increment = body->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(1))); induction_variable = body->AddInstruction(HloInstruction::CreateBinary( shape, HloOpcode::kAdd, induction_variable, increment)); HloInstruction* new_root = TupleUtil::AppendSuffix(old_root, {induction_variable}); body->set_root_instruction(new_root, /*accept_different_shape=*/true); } // Snapshot the users of while hlo before we add new users. std::vector<HloInstruction*> while_users(while_hlo->users().begin(), while_hlo->users().end()); // Take care of the users of this while loop. TF_RETURN_IF_ERROR(change_op_shape(while_hlo)); TF_ASSIGN_OR_RETURN(HloInstruction * prefix, replace_non_gte_users(while_hlo)); // If the while loop had been the root of its computation, make the prefix new // root. if (while_hlo->parent()->root_instruction() == while_hlo) { // We need to set accept_different_shape=true to reset the root shape to the // original, because we have already changed the shape of the old root // (while). if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix(while_hlo, new_tuple_size - 1); } while_hlo->parent()->set_root_instruction(prefix, /*accept_different_shape=*/true); } return absl::OkStatus(); } auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); VLOG(1) << "loop_bound = " << loop_bound; absl::Status HloControlFlowFlattening::RemoveInfeed( HloInstruction* infeed_hlo) const { CHECK_EQ(infeed_hlo->opcode(), HloOpcode::kInfeed); HloComputation* computation = infeed_hlo->parent(); CHECK_EQ(infeed_hlo->shape().tuple_shapes_size(), 2); const Shape& infeed_shape = ShapeUtil::GetSubshape(infeed_hlo->shape(), {0}); HloInstruction* custom_call = computation->AddInstruction( HloInstruction::CreateCustomCall(infeed_shape, {}, kNopCustomCallTarget)); // Create a new tuple consisting of the constant and the token that was // originally the operand of infeed, and replace the infeed operation. auto new_tuple = HloInstruction::CreateTuple( {custom_call, infeed_hlo->mutable_operand(0)}); TF_RETURN_IF_ERROR( computation->ReplaceWithNewInstruction(infeed_hlo, std::move(new_tuple))); custom_call->SetAndSanitizeName(infeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveRecvAndRecvDone( HloInstruction* recv_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(recv_done->opcode(), HloOpcode::kRecvDone); CHECK_EQ(recv_done->operand_count(), 1); HloInstruction* recv = recv_done->mutable_operand(0); CHECK_EQ(recv->opcode(), HloOpcode::kRecv); HloComputation* computation = recv_done->parent(); CHECK_EQ(recv_done->shape().tuple_shapes_size(), 2); HloModule* module = computation->parent(); HloInstruction* custom_call_recv = computation->AddInstruction(HloInstruction::CreateCustomCall( recv->shape(), recv->operands(), kNopCustomCallTarget)); std::string original_recv_name(recv->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv, custom_call_recv); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(recv, custom_call_recv)); custom_call_recv->SetAndSanitizeName(original_recv_name); std::string original_recv_done_name(recv_done->name()); HloInstruction* custom_call_recv_done = computation->AddInstruction( HloInstruction::CreateCustomCall( recv_done->shape(), recv_done->operands(), kNopCustomCallTarget), recv_done->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv_done, custom_call_recv_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(recv_done, custom_call_recv_done)); custom_call_recv_done->SetAndSanitizeName(original_recv_done_name); return std::make_pair(custom_call_recv, custom_call_recv_done); } absl::Status HloControlFlowFlattening::RemoveOutfeed( HloInstruction* outfeed_hlo) const { CHECK_EQ(outfeed_hlo->opcode(), HloOpcode::kOutfeed); HloComputation* computation = outfeed_hlo->parent(); // Replace the outfeed with a no-op custom call with side effect to ensure the // operands aren't DCE'd. HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( outfeed_hlo->shape(), outfeed_hlo->operands(), kNopReturnTokenCustomCallTarget)); Cast<HloCustomCallInstruction>(custom_call) ->set_custom_call_has_side_effect(true); // For SPMD graphs, partitioner requires that side-effecting custom calls have // a sharding that is non-replicated. custom_call->set_sharding(HloSharding::Manual()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(outfeed_hlo, custom_call)); custom_call->SetAndSanitizeName(outfeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveSendAndSendDone( HloInstruction* send_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(send_done->opcode(), HloOpcode::kSendDone); CHECK_EQ(send_done->operand_count(), 1); HloInstruction* send = send_done->mutable_operand(0); CHECK_EQ(send->opcode(), HloOpcode::kSend); HloComputation* computation = send_done->parent(); HloModule* module = computation->parent(); HloInstruction* custom_call_send = computation->AddInstruction(HloInstruction::CreateCustomCall( send->shape(), send->operands(), kNopCustomCallTarget)); std::string original_send_name(send->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send, custom_call_send); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(send, custom_call_send)); custom_call_send->SetAndSanitizeName(original_send_name); HloInstruction* custom_call_send_done = computation->AddInstruction(HloInstruction::CreateCustomCall( send_done->shape(), send_done->operands(), kNopReturnTokenCustomCallTarget)); std::string original_send_done_name(send_done->name()); Cast<HloCustomCallInstruction>(custom_call_send_done) ->set_custom_call_has_side_effect(true); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send_done, custom_call_send_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(send_done, custom_call_send_done)); custom_call_send_done->SetAndSanitizeName(original_send_done_name); return std::make_pair(custom_call_send, custom_call_send_done); } absl::StatusOr<HloInstruction*> HloControlFlowFlattening::RemoveCollective( HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( hlo->shape(), hlo->operands(), kNopCustomCallTarget)); // Copy backend config. This is necessary for a collective op in megacore // fusion. custom_call->CopyBackendConfigFrom(hlo); HloModule* module = computation->parent(); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, hlo, custom_call); } std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, custom_call)); custom_call->SetAndSanitizeName(original_op_name); return custom_call; } absl::Status HloControlFlowFlattening::RemoveId(HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* zero = CreateConstant(hlo->shape(), computation); std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, zero)); zero->SetAndSanitizeName(original_op_name); return absl::OkStatus(); } absl::StatusOr<bool> HloControlFlowFlattening::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { auto call_graph = CallGraph::Build(module); bool changed = false; absl::flat_hash_set<HloInstruction*> removed; for (HloComputation* computation : module->computations(execution_threads)) { // Do not change computations that are wrapped by async calls. Instead we // remove the async callers if needed. if (computation->IsAsyncComputation()) { continue; } for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (removed.contains(instruction)) { // Skip the instruction if it is already removed. continue; } if (flatten_while_loop_ && instruction->opcode() == HloOpcode::kWhile) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(FlattenWhileLoop(instruction, *call_graph)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kInfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveInfeed(instruction)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kOutfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveOutfeed(instruction)); changed = true; } else if (instruction->opcode() == HloOpcode::kSendDone) { auto send_done_instruction = DynCast<HloSendDoneInstruction>(instruction); CHECK(send_done_instruction); if (remove_comm_ || (remove_host_transfer_ && send_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveSendAndSendDone(instruction, &removed).status()); changed = true; } } else if (instruction->opcode() == HloOpcode::kRecvDone) { auto recv_done_instruction = DynCast<HloRecvDoneInstruction>(instruction); CHECK(recv_done_instruction); if (remove_comm_ || (remove_host_transfer_ && recv_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveRecvAndRecvDone(instruction, &removed).status()); changed = true; } } else if (remove_comm_ && IsCollective(instruction) && !instruction->parent()->IsFusionComputation() && (instruction->opcode() != HloOpcode::kAsyncStart && instruction->opcode() != HloOpcode::kAsyncUpdate)) { // We do not remove kAsyncStart or kAsyncUpdate here since we expect // them to be removed as a part of the async chain above. // We should remove the async chain all together because the async // wrapped computation is only associated with the AsyncStart. So we // need to refer to the AsyncStart in order to determine whether // the Done or the Update wraps a collective. if (instruction->opcode() == HloOpcode::kAsyncDone) { while (instruction->opcode() == HloOpcode::kAsyncDone || instruction->opcode() == HloOpcode::kAsyncUpdate || instruction->opcode() == HloOpcode::kAsyncStart) { HloInstruction* operand = instruction->mutable_operand(0); VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); instruction = operand; } } else { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); } changed = true; } else if (remove_comm_ && (instruction->opcode() == HloOpcode::kPartitionId || instruction->opcode() == HloOpcode::kReplicaId || (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == "SliceId"))) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveId(instruction)); changed = true; } } } HloDCE hlo_dce; TF_ASSIGN_OR_RETURN(bool dce_changed, hlo_dce.Run(module, execution_threads)); changed |= dce_changed; // Fix the schedule if the module was scheduled. if (changed && module->has_schedule()) { TF_RETURN_IF_ERROR(module->schedule().Update()); } XLA_VLOG_LINES(3, module->ToString()); return changed; } VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); XLA_VLOG_LINES(3, module->ToString());
#include "xla/tools/hlo_control_flow_flattening.h" #include <memory> #include <utility> #include "absl/strings/str_replace.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/collective_ops_utils.h" #include "xla/service/despecializer.h" #include "xla/service/hlo_verifier.h" #include "xla/service/spmd/spmd_partitioner.h" #include "xla/tests/hlo_test_base.h" #include "tsl/lib/core/status_test_util.h" class HloControlFlowFlatteningTest : public HloTestBase { public: absl::StatusOr<std::unique_ptr<HloModule>> PartitionComputation( std::unique_ptr<VerifiedHloModule> hlo_module, int64_t num_devices = 2) { spmd::SpmdPartitionerOptions options; auto collective_ops_creator = spmd::GetDefaultCollectiveOpsCreator(num_devices, /*num_replicas=*/1); collective_ops_creator.create_cross_partition_all_gather = nullptr; HloModuleConfig config = GetModuleConfigForTest(); config.set_use_spmd_partitioning(true); config.set_num_partitions(num_devices); HloPassPipeline pass("spmd-partitioning"); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); pass.AddPass<spmd::SpmdPartitioner>(num_devices, /*num_replicas=*/1, options, collective_ops_creator); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); TF_RETURN_IF_ERROR(pass.Run(hlo_module.get()).status()); return absl::StatusOr<std::unique_ptr<HloModule>>(std::move(hlo_module)); } };
HloControlFlowFlatteningTest_CollectiveFusion
xla/tools/hlo_control_flow_flattening_test.cc
HloInstruction* CreateConstant(const Shape& shape, HloComputation* computation) { if (shape.IsTuple()) { std::vector<HloInstruction*> tuple_arguments(shape.tuple_shapes_size()); for (int index = 0; index < shape.tuple_shapes_size(); ++index) { tuple_arguments[index] = CreateConstant(shape.tuple_shapes(index), computation); } return computation->AddInstruction( HloInstruction::CreateTuple(tuple_arguments)); } else { return computation->AddInstruction( HloInstruction::CreateConstant(Literal::CreateFromShape(shape))); } } void PrintSubexpression(HloInstruction* inst, int depth) { if (depth == 0) { return; } for (auto* operand : inst->operands()) { PrintSubexpression(operand, depth - 1); } VLOG(2) << inst->ToString(); } VLOG(2) << inst->ToString(); bool IsConstantScalarInt(const HloInstruction* inst) { return inst->opcode() == HloOpcode::kConstant && ShapeUtil::IsEffectiveScalar(inst->shape()) && inst->shape().IsInteger(); } bool IsNotContainedInLoop(const HloInstruction& while_hlo, const CallGraph& call_graph) { const HloComputation* computation = while_hlo.parent(); while (!computation->IsEntryComputation()) { auto& node = call_graph.GetNode(computation); CHECK_EQ(node.caller_callsites().size(), 1) << "The module is not flattened!"; auto& callsite = node.caller_callsites()[0]; if (callsite.instruction()->opcode() == HloOpcode::kWhile) { // Another while loop has been found traversing up the call tree. return false; } computation = callsite.instruction()->parent(); } // No calling while loops were found. return true; } int GetLoopBound(const HloInstruction& while_hlo, const int default_loop_count, const int max_loop_count) { HloInstruction* condition = while_hlo.while_condition()->root_instruction(); if (condition->opcode() == HloOpcode::kCompare) { int64_t value = 0; Comparison::Direction cmp = condition->comparison_direction(); if ((cmp == Comparison::Direction::kLt || cmp == Comparison::Direction::kLe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(1))) { value = *condition->operand(1)->literal().GetFirstInteger(); } else if ((cmp == Comparison::Direction::kGt || cmp == Comparison::Direction::kGe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(0))) { value = *condition->operand(0)->literal().GetFirstInteger(); } if (value > 0) { // Caps to a max loop count to avoid long execution times. return std::min(value, static_cast<int64_t>(max_loop_count)); } } return default_loop_count; } int GetLoopBoundWithOuterLoopMax(const HloInstruction& while_hlo, const CallGraph& call_graph, const int default_loop_count, const int max_outer_loop_count, const int max_loop_count) { int loop_bound = GetLoopBound(while_hlo, default_loop_count, max_loop_count); if (loop_bound > max_outer_loop_count) { // First does the inexpensive loop bound check to avoid as many // expensive graph traversals in IsNotContainedInLoop as possible. if (IsNotContainedInLoop(while_hlo, call_graph)) { return max_outer_loop_count; } } return loop_bound; } absl::Status HloControlFlowFlattening::FlattenWhileLoop( HloInstruction* while_hlo, const CallGraph& call_graph) const { CHECK_EQ(while_hlo->opcode(), HloOpcode::kWhile); HloComputation* computation = while_hlo->parent(); // Add a new induction variable. HloInstruction* initialization = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(0))); // Create a new while operand with the induction variable added. HloInstruction* old_tuple = while_hlo->mutable_operand(0); HloInstruction* new_tuple = TupleUtil::AppendSuffix(old_tuple, {initialization}); int new_tuple_size = new_tuple->shape().tuple_shapes().size(); TF_RETURN_IF_ERROR(while_hlo->ReplaceOperandWithDifferentShape(0, new_tuple)); auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; // Replace the given tuple-shaped instruction of size N in each of its // non-get-tuple-element users with a new tuple instruction which has the // first N - 1 elements. auto replace_non_gte_users = [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; { // Add the new variable to the while loop condition. HloComputation* condition = while_hlo->while_condition(); TF_RETURN_IF_ERROR(change_op_shape(condition->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(condition->parameter_instruction(0)).status()); if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); PrintSubexpression(condition->root_instruction(), /*depth=*/3); } const int loop_bound = GetLoopBoundWithOuterLoopMax( *while_hlo, call_graph, while_execution_count_, max_outer_loop_count_, max_loop_count_); VLOG(1) << "loop_bound = " << loop_bound; HloInstruction* limit = condition->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(loop_bound))); Shape shape = initialization->shape(); HloInstruction* induction_variable = condition->AddInstruction(HloInstruction::CreateGetTupleElement( shape, condition->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* compare = condition->AddInstruction(HloInstruction::CreateCompare( ShapeUtil::MakeShape(PRED, {}), induction_variable, limit, ComparisonDirection::kLt)); TF_RETURN_IF_ERROR( condition->ReplaceInstruction(condition->root_instruction(), compare)); } { // Add the new variable to the while loop body. HloComputation* body = while_hlo->while_body(); TF_RETURN_IF_ERROR(change_op_shape(body->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(body->parameter_instruction(0)).status()); HloInstruction* old_root = body->root_instruction(); Shape shape = initialization->shape(); HloInstruction* induction_variable = body->AddInstruction(HloInstruction::CreateGetTupleElement( shape, body->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* increment = body->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(1))); induction_variable = body->AddInstruction(HloInstruction::CreateBinary( shape, HloOpcode::kAdd, induction_variable, increment)); HloInstruction* new_root = TupleUtil::AppendSuffix(old_root, {induction_variable}); body->set_root_instruction(new_root, /*accept_different_shape=*/true); } // Snapshot the users of while hlo before we add new users. std::vector<HloInstruction*> while_users(while_hlo->users().begin(), while_hlo->users().end()); // Take care of the users of this while loop. TF_RETURN_IF_ERROR(change_op_shape(while_hlo)); TF_ASSIGN_OR_RETURN(HloInstruction * prefix, replace_non_gte_users(while_hlo)); // If the while loop had been the root of its computation, make the prefix new // root. if (while_hlo->parent()->root_instruction() == while_hlo) { // We need to set accept_different_shape=true to reset the root shape to the // original, because we have already changed the shape of the old root // (while). if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix(while_hlo, new_tuple_size - 1); } while_hlo->parent()->set_root_instruction(prefix, /*accept_different_shape=*/true); } return absl::OkStatus(); } auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); VLOG(1) << "loop_bound = " << loop_bound; absl::Status HloControlFlowFlattening::RemoveInfeed( HloInstruction* infeed_hlo) const { CHECK_EQ(infeed_hlo->opcode(), HloOpcode::kInfeed); HloComputation* computation = infeed_hlo->parent(); CHECK_EQ(infeed_hlo->shape().tuple_shapes_size(), 2); const Shape& infeed_shape = ShapeUtil::GetSubshape(infeed_hlo->shape(), {0}); HloInstruction* custom_call = computation->AddInstruction( HloInstruction::CreateCustomCall(infeed_shape, {}, kNopCustomCallTarget)); // Create a new tuple consisting of the constant and the token that was // originally the operand of infeed, and replace the infeed operation. auto new_tuple = HloInstruction::CreateTuple( {custom_call, infeed_hlo->mutable_operand(0)}); TF_RETURN_IF_ERROR( computation->ReplaceWithNewInstruction(infeed_hlo, std::move(new_tuple))); custom_call->SetAndSanitizeName(infeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveRecvAndRecvDone( HloInstruction* recv_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(recv_done->opcode(), HloOpcode::kRecvDone); CHECK_EQ(recv_done->operand_count(), 1); HloInstruction* recv = recv_done->mutable_operand(0); CHECK_EQ(recv->opcode(), HloOpcode::kRecv); HloComputation* computation = recv_done->parent(); CHECK_EQ(recv_done->shape().tuple_shapes_size(), 2); HloModule* module = computation->parent(); HloInstruction* custom_call_recv = computation->AddInstruction(HloInstruction::CreateCustomCall( recv->shape(), recv->operands(), kNopCustomCallTarget)); std::string original_recv_name(recv->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv, custom_call_recv); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(recv, custom_call_recv)); custom_call_recv->SetAndSanitizeName(original_recv_name); std::string original_recv_done_name(recv_done->name()); HloInstruction* custom_call_recv_done = computation->AddInstruction( HloInstruction::CreateCustomCall( recv_done->shape(), recv_done->operands(), kNopCustomCallTarget), recv_done->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv_done, custom_call_recv_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(recv_done, custom_call_recv_done)); custom_call_recv_done->SetAndSanitizeName(original_recv_done_name); return std::make_pair(custom_call_recv, custom_call_recv_done); } absl::Status HloControlFlowFlattening::RemoveOutfeed( HloInstruction* outfeed_hlo) const { CHECK_EQ(outfeed_hlo->opcode(), HloOpcode::kOutfeed); HloComputation* computation = outfeed_hlo->parent(); // Replace the outfeed with a no-op custom call with side effect to ensure the // operands aren't DCE'd. HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( outfeed_hlo->shape(), outfeed_hlo->operands(), kNopReturnTokenCustomCallTarget)); Cast<HloCustomCallInstruction>(custom_call) ->set_custom_call_has_side_effect(true); // For SPMD graphs, partitioner requires that side-effecting custom calls have // a sharding that is non-replicated. custom_call->set_sharding(HloSharding::Manual()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(outfeed_hlo, custom_call)); custom_call->SetAndSanitizeName(outfeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveSendAndSendDone( HloInstruction* send_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(send_done->opcode(), HloOpcode::kSendDone); CHECK_EQ(send_done->operand_count(), 1); HloInstruction* send = send_done->mutable_operand(0); CHECK_EQ(send->opcode(), HloOpcode::kSend); HloComputation* computation = send_done->parent(); HloModule* module = computation->parent(); HloInstruction* custom_call_send = computation->AddInstruction(HloInstruction::CreateCustomCall( send->shape(), send->operands(), kNopCustomCallTarget)); std::string original_send_name(send->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send, custom_call_send); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(send, custom_call_send)); custom_call_send->SetAndSanitizeName(original_send_name); HloInstruction* custom_call_send_done = computation->AddInstruction(HloInstruction::CreateCustomCall( send_done->shape(), send_done->operands(), kNopReturnTokenCustomCallTarget)); std::string original_send_done_name(send_done->name()); Cast<HloCustomCallInstruction>(custom_call_send_done) ->set_custom_call_has_side_effect(true); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send_done, custom_call_send_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(send_done, custom_call_send_done)); custom_call_send_done->SetAndSanitizeName(original_send_done_name); return std::make_pair(custom_call_send, custom_call_send_done); } absl::StatusOr<HloInstruction*> HloControlFlowFlattening::RemoveCollective( HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( hlo->shape(), hlo->operands(), kNopCustomCallTarget)); // Copy backend config. This is necessary for a collective op in megacore // fusion. custom_call->CopyBackendConfigFrom(hlo); HloModule* module = computation->parent(); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, hlo, custom_call); } std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, custom_call)); custom_call->SetAndSanitizeName(original_op_name); return custom_call; } absl::Status HloControlFlowFlattening::RemoveId(HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* zero = CreateConstant(hlo->shape(), computation); std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, zero)); zero->SetAndSanitizeName(original_op_name); return absl::OkStatus(); } absl::StatusOr<bool> HloControlFlowFlattening::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { auto call_graph = CallGraph::Build(module); bool changed = false; absl::flat_hash_set<HloInstruction*> removed; for (HloComputation* computation : module->computations(execution_threads)) { // Do not change computations that are wrapped by async calls. Instead we // remove the async callers if needed. if (computation->IsAsyncComputation()) { continue; } for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (removed.contains(instruction)) { // Skip the instruction if it is already removed. continue; } if (flatten_while_loop_ && instruction->opcode() == HloOpcode::kWhile) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(FlattenWhileLoop(instruction, *call_graph)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kInfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveInfeed(instruction)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kOutfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveOutfeed(instruction)); changed = true; } else if (instruction->opcode() == HloOpcode::kSendDone) { auto send_done_instruction = DynCast<HloSendDoneInstruction>(instruction); CHECK(send_done_instruction); if (remove_comm_ || (remove_host_transfer_ && send_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveSendAndSendDone(instruction, &removed).status()); changed = true; } } else if (instruction->opcode() == HloOpcode::kRecvDone) { auto recv_done_instruction = DynCast<HloRecvDoneInstruction>(instruction); CHECK(recv_done_instruction); if (remove_comm_ || (remove_host_transfer_ && recv_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveRecvAndRecvDone(instruction, &removed).status()); changed = true; } } else if (remove_comm_ && IsCollective(instruction) && !instruction->parent()->IsFusionComputation() && (instruction->opcode() != HloOpcode::kAsyncStart && instruction->opcode() != HloOpcode::kAsyncUpdate)) { // We do not remove kAsyncStart or kAsyncUpdate here since we expect // them to be removed as a part of the async chain above. // We should remove the async chain all together because the async // wrapped computation is only associated with the AsyncStart. So we // need to refer to the AsyncStart in order to determine whether // the Done or the Update wraps a collective. if (instruction->opcode() == HloOpcode::kAsyncDone) { while (instruction->opcode() == HloOpcode::kAsyncDone || instruction->opcode() == HloOpcode::kAsyncUpdate || instruction->opcode() == HloOpcode::kAsyncStart) { HloInstruction* operand = instruction->mutable_operand(0); VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); instruction = operand; } } else { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); } changed = true; } else if (remove_comm_ && (instruction->opcode() == HloOpcode::kPartitionId || instruction->opcode() == HloOpcode::kReplicaId || (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == "SliceId"))) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveId(instruction)); changed = true; } } } HloDCE hlo_dce; TF_ASSIGN_OR_RETURN(bool dce_changed, hlo_dce.Run(module, execution_threads)); changed |= dce_changed; // Fix the schedule if the module was scheduled. if (changed && module->has_schedule()) { TF_RETURN_IF_ERROR(module->schedule().Update()); } XLA_VLOG_LINES(3, module->ToString()); return changed; } VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); XLA_VLOG_LINES(3, module->ToString());
#include "xla/tools/hlo_control_flow_flattening.h" #include <memory> #include <utility> #include "absl/strings/str_replace.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/collective_ops_utils.h" #include "xla/service/despecializer.h" #include "xla/service/hlo_verifier.h" #include "xla/service/spmd/spmd_partitioner.h" #include "xla/tests/hlo_test_base.h" #include "tsl/lib/core/status_test_util.h" class HloControlFlowFlatteningTest : public HloTestBase { public: absl::StatusOr<std::unique_ptr<HloModule>> PartitionComputation( std::unique_ptr<VerifiedHloModule> hlo_module, int64_t num_devices = 2) { spmd::SpmdPartitionerOptions options; auto collective_ops_creator = spmd::GetDefaultCollectiveOpsCreator(num_devices, /*num_replicas=*/1); collective_ops_creator.create_cross_partition_all_gather = nullptr; HloModuleConfig config = GetModuleConfigForTest(); config.set_use_spmd_partitioning(true); config.set_num_partitions(num_devices); HloPassPipeline pass("spmd-partitioning"); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); pass.AddPass<spmd::SpmdPartitioner>(num_devices, /*num_replicas=*/1, options, collective_ops_creator); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); TF_RETURN_IF_ERROR(pass.Run(hlo_module.get()).status()); return absl::StatusOr<std::unique_ptr<HloModule>>(std::move(hlo_module)); } };
HloControlFlowFlatteningTest_CollectivePermute
xla/tools/hlo_control_flow_flattening_test.cc
HloInstruction* CreateConstant(const Shape& shape, HloComputation* computation) { if (shape.IsTuple()) { std::vector<HloInstruction*> tuple_arguments(shape.tuple_shapes_size()); for (int index = 0; index < shape.tuple_shapes_size(); ++index) { tuple_arguments[index] = CreateConstant(shape.tuple_shapes(index), computation); } return computation->AddInstruction( HloInstruction::CreateTuple(tuple_arguments)); } else { return computation->AddInstruction( HloInstruction::CreateConstant(Literal::CreateFromShape(shape))); } } void PrintSubexpression(HloInstruction* inst, int depth) { if (depth == 0) { return; } for (auto* operand : inst->operands()) { PrintSubexpression(operand, depth - 1); } VLOG(2) << inst->ToString(); } VLOG(2) << inst->ToString(); bool IsConstantScalarInt(const HloInstruction* inst) { return inst->opcode() == HloOpcode::kConstant && ShapeUtil::IsEffectiveScalar(inst->shape()) && inst->shape().IsInteger(); } bool IsNotContainedInLoop(const HloInstruction& while_hlo, const CallGraph& call_graph) { const HloComputation* computation = while_hlo.parent(); while (!computation->IsEntryComputation()) { auto& node = call_graph.GetNode(computation); CHECK_EQ(node.caller_callsites().size(), 1) << "The module is not flattened!"; auto& callsite = node.caller_callsites()[0]; if (callsite.instruction()->opcode() == HloOpcode::kWhile) { // Another while loop has been found traversing up the call tree. return false; } computation = callsite.instruction()->parent(); } // No calling while loops were found. return true; } int GetLoopBound(const HloInstruction& while_hlo, const int default_loop_count, const int max_loop_count) { HloInstruction* condition = while_hlo.while_condition()->root_instruction(); if (condition->opcode() == HloOpcode::kCompare) { int64_t value = 0; Comparison::Direction cmp = condition->comparison_direction(); if ((cmp == Comparison::Direction::kLt || cmp == Comparison::Direction::kLe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(1))) { value = *condition->operand(1)->literal().GetFirstInteger(); } else if ((cmp == Comparison::Direction::kGt || cmp == Comparison::Direction::kGe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(0))) { value = *condition->operand(0)->literal().GetFirstInteger(); } if (value > 0) { // Caps to a max loop count to avoid long execution times. return std::min(value, static_cast<int64_t>(max_loop_count)); } } return default_loop_count; } int GetLoopBoundWithOuterLoopMax(const HloInstruction& while_hlo, const CallGraph& call_graph, const int default_loop_count, const int max_outer_loop_count, const int max_loop_count) { int loop_bound = GetLoopBound(while_hlo, default_loop_count, max_loop_count); if (loop_bound > max_outer_loop_count) { // First does the inexpensive loop bound check to avoid as many // expensive graph traversals in IsNotContainedInLoop as possible. if (IsNotContainedInLoop(while_hlo, call_graph)) { return max_outer_loop_count; } } return loop_bound; } absl::Status HloControlFlowFlattening::FlattenWhileLoop( HloInstruction* while_hlo, const CallGraph& call_graph) const { CHECK_EQ(while_hlo->opcode(), HloOpcode::kWhile); HloComputation* computation = while_hlo->parent(); // Add a new induction variable. HloInstruction* initialization = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(0))); // Create a new while operand with the induction variable added. HloInstruction* old_tuple = while_hlo->mutable_operand(0); HloInstruction* new_tuple = TupleUtil::AppendSuffix(old_tuple, {initialization}); int new_tuple_size = new_tuple->shape().tuple_shapes().size(); TF_RETURN_IF_ERROR(while_hlo->ReplaceOperandWithDifferentShape(0, new_tuple)); auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; // Replace the given tuple-shaped instruction of size N in each of its // non-get-tuple-element users with a new tuple instruction which has the // first N - 1 elements. auto replace_non_gte_users = [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; { // Add the new variable to the while loop condition. HloComputation* condition = while_hlo->while_condition(); TF_RETURN_IF_ERROR(change_op_shape(condition->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(condition->parameter_instruction(0)).status()); if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); PrintSubexpression(condition->root_instruction(), /*depth=*/3); } const int loop_bound = GetLoopBoundWithOuterLoopMax( *while_hlo, call_graph, while_execution_count_, max_outer_loop_count_, max_loop_count_); VLOG(1) << "loop_bound = " << loop_bound; HloInstruction* limit = condition->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(loop_bound))); Shape shape = initialization->shape(); HloInstruction* induction_variable = condition->AddInstruction(HloInstruction::CreateGetTupleElement( shape, condition->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* compare = condition->AddInstruction(HloInstruction::CreateCompare( ShapeUtil::MakeShape(PRED, {}), induction_variable, limit, ComparisonDirection::kLt)); TF_RETURN_IF_ERROR( condition->ReplaceInstruction(condition->root_instruction(), compare)); } { // Add the new variable to the while loop body. HloComputation* body = while_hlo->while_body(); TF_RETURN_IF_ERROR(change_op_shape(body->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(body->parameter_instruction(0)).status()); HloInstruction* old_root = body->root_instruction(); Shape shape = initialization->shape(); HloInstruction* induction_variable = body->AddInstruction(HloInstruction::CreateGetTupleElement( shape, body->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* increment = body->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(1))); induction_variable = body->AddInstruction(HloInstruction::CreateBinary( shape, HloOpcode::kAdd, induction_variable, increment)); HloInstruction* new_root = TupleUtil::AppendSuffix(old_root, {induction_variable}); body->set_root_instruction(new_root, /*accept_different_shape=*/true); } // Snapshot the users of while hlo before we add new users. std::vector<HloInstruction*> while_users(while_hlo->users().begin(), while_hlo->users().end()); // Take care of the users of this while loop. TF_RETURN_IF_ERROR(change_op_shape(while_hlo)); TF_ASSIGN_OR_RETURN(HloInstruction * prefix, replace_non_gte_users(while_hlo)); // If the while loop had been the root of its computation, make the prefix new // root. if (while_hlo->parent()->root_instruction() == while_hlo) { // We need to set accept_different_shape=true to reset the root shape to the // original, because we have already changed the shape of the old root // (while). if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix(while_hlo, new_tuple_size - 1); } while_hlo->parent()->set_root_instruction(prefix, /*accept_different_shape=*/true); } return absl::OkStatus(); } auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); VLOG(1) << "loop_bound = " << loop_bound; absl::Status HloControlFlowFlattening::RemoveInfeed( HloInstruction* infeed_hlo) const { CHECK_EQ(infeed_hlo->opcode(), HloOpcode::kInfeed); HloComputation* computation = infeed_hlo->parent(); CHECK_EQ(infeed_hlo->shape().tuple_shapes_size(), 2); const Shape& infeed_shape = ShapeUtil::GetSubshape(infeed_hlo->shape(), {0}); HloInstruction* custom_call = computation->AddInstruction( HloInstruction::CreateCustomCall(infeed_shape, {}, kNopCustomCallTarget)); // Create a new tuple consisting of the constant and the token that was // originally the operand of infeed, and replace the infeed operation. auto new_tuple = HloInstruction::CreateTuple( {custom_call, infeed_hlo->mutable_operand(0)}); TF_RETURN_IF_ERROR( computation->ReplaceWithNewInstruction(infeed_hlo, std::move(new_tuple))); custom_call->SetAndSanitizeName(infeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveRecvAndRecvDone( HloInstruction* recv_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(recv_done->opcode(), HloOpcode::kRecvDone); CHECK_EQ(recv_done->operand_count(), 1); HloInstruction* recv = recv_done->mutable_operand(0); CHECK_EQ(recv->opcode(), HloOpcode::kRecv); HloComputation* computation = recv_done->parent(); CHECK_EQ(recv_done->shape().tuple_shapes_size(), 2); HloModule* module = computation->parent(); HloInstruction* custom_call_recv = computation->AddInstruction(HloInstruction::CreateCustomCall( recv->shape(), recv->operands(), kNopCustomCallTarget)); std::string original_recv_name(recv->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv, custom_call_recv); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(recv, custom_call_recv)); custom_call_recv->SetAndSanitizeName(original_recv_name); std::string original_recv_done_name(recv_done->name()); HloInstruction* custom_call_recv_done = computation->AddInstruction( HloInstruction::CreateCustomCall( recv_done->shape(), recv_done->operands(), kNopCustomCallTarget), recv_done->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv_done, custom_call_recv_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(recv_done, custom_call_recv_done)); custom_call_recv_done->SetAndSanitizeName(original_recv_done_name); return std::make_pair(custom_call_recv, custom_call_recv_done); } absl::Status HloControlFlowFlattening::RemoveOutfeed( HloInstruction* outfeed_hlo) const { CHECK_EQ(outfeed_hlo->opcode(), HloOpcode::kOutfeed); HloComputation* computation = outfeed_hlo->parent(); // Replace the outfeed with a no-op custom call with side effect to ensure the // operands aren't DCE'd. HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( outfeed_hlo->shape(), outfeed_hlo->operands(), kNopReturnTokenCustomCallTarget)); Cast<HloCustomCallInstruction>(custom_call) ->set_custom_call_has_side_effect(true); // For SPMD graphs, partitioner requires that side-effecting custom calls have // a sharding that is non-replicated. custom_call->set_sharding(HloSharding::Manual()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(outfeed_hlo, custom_call)); custom_call->SetAndSanitizeName(outfeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveSendAndSendDone( HloInstruction* send_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(send_done->opcode(), HloOpcode::kSendDone); CHECK_EQ(send_done->operand_count(), 1); HloInstruction* send = send_done->mutable_operand(0); CHECK_EQ(send->opcode(), HloOpcode::kSend); HloComputation* computation = send_done->parent(); HloModule* module = computation->parent(); HloInstruction* custom_call_send = computation->AddInstruction(HloInstruction::CreateCustomCall( send->shape(), send->operands(), kNopCustomCallTarget)); std::string original_send_name(send->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send, custom_call_send); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(send, custom_call_send)); custom_call_send->SetAndSanitizeName(original_send_name); HloInstruction* custom_call_send_done = computation->AddInstruction(HloInstruction::CreateCustomCall( send_done->shape(), send_done->operands(), kNopReturnTokenCustomCallTarget)); std::string original_send_done_name(send_done->name()); Cast<HloCustomCallInstruction>(custom_call_send_done) ->set_custom_call_has_side_effect(true); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send_done, custom_call_send_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(send_done, custom_call_send_done)); custom_call_send_done->SetAndSanitizeName(original_send_done_name); return std::make_pair(custom_call_send, custom_call_send_done); } absl::StatusOr<HloInstruction*> HloControlFlowFlattening::RemoveCollective( HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( hlo->shape(), hlo->operands(), kNopCustomCallTarget)); // Copy backend config. This is necessary for a collective op in megacore // fusion. custom_call->CopyBackendConfigFrom(hlo); HloModule* module = computation->parent(); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, hlo, custom_call); } std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, custom_call)); custom_call->SetAndSanitizeName(original_op_name); return custom_call; } absl::Status HloControlFlowFlattening::RemoveId(HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* zero = CreateConstant(hlo->shape(), computation); std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, zero)); zero->SetAndSanitizeName(original_op_name); return absl::OkStatus(); } absl::StatusOr<bool> HloControlFlowFlattening::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { auto call_graph = CallGraph::Build(module); bool changed = false; absl::flat_hash_set<HloInstruction*> removed; for (HloComputation* computation : module->computations(execution_threads)) { // Do not change computations that are wrapped by async calls. Instead we // remove the async callers if needed. if (computation->IsAsyncComputation()) { continue; } for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (removed.contains(instruction)) { // Skip the instruction if it is already removed. continue; } if (flatten_while_loop_ && instruction->opcode() == HloOpcode::kWhile) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(FlattenWhileLoop(instruction, *call_graph)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kInfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveInfeed(instruction)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kOutfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveOutfeed(instruction)); changed = true; } else if (instruction->opcode() == HloOpcode::kSendDone) { auto send_done_instruction = DynCast<HloSendDoneInstruction>(instruction); CHECK(send_done_instruction); if (remove_comm_ || (remove_host_transfer_ && send_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveSendAndSendDone(instruction, &removed).status()); changed = true; } } else if (instruction->opcode() == HloOpcode::kRecvDone) { auto recv_done_instruction = DynCast<HloRecvDoneInstruction>(instruction); CHECK(recv_done_instruction); if (remove_comm_ || (remove_host_transfer_ && recv_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveRecvAndRecvDone(instruction, &removed).status()); changed = true; } } else if (remove_comm_ && IsCollective(instruction) && !instruction->parent()->IsFusionComputation() && (instruction->opcode() != HloOpcode::kAsyncStart && instruction->opcode() != HloOpcode::kAsyncUpdate)) { // We do not remove kAsyncStart or kAsyncUpdate here since we expect // them to be removed as a part of the async chain above. // We should remove the async chain all together because the async // wrapped computation is only associated with the AsyncStart. So we // need to refer to the AsyncStart in order to determine whether // the Done or the Update wraps a collective. if (instruction->opcode() == HloOpcode::kAsyncDone) { while (instruction->opcode() == HloOpcode::kAsyncDone || instruction->opcode() == HloOpcode::kAsyncUpdate || instruction->opcode() == HloOpcode::kAsyncStart) { HloInstruction* operand = instruction->mutable_operand(0); VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); instruction = operand; } } else { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); } changed = true; } else if (remove_comm_ && (instruction->opcode() == HloOpcode::kPartitionId || instruction->opcode() == HloOpcode::kReplicaId || (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == "SliceId"))) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveId(instruction)); changed = true; } } } HloDCE hlo_dce; TF_ASSIGN_OR_RETURN(bool dce_changed, hlo_dce.Run(module, execution_threads)); changed |= dce_changed; // Fix the schedule if the module was scheduled. if (changed && module->has_schedule()) { TF_RETURN_IF_ERROR(module->schedule().Update()); } XLA_VLOG_LINES(3, module->ToString()); return changed; } VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); XLA_VLOG_LINES(3, module->ToString());
#include "xla/tools/hlo_control_flow_flattening.h" #include <memory> #include <utility> #include "absl/strings/str_replace.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/collective_ops_utils.h" #include "xla/service/despecializer.h" #include "xla/service/hlo_verifier.h" #include "xla/service/spmd/spmd_partitioner.h" #include "xla/tests/hlo_test_base.h" #include "tsl/lib/core/status_test_util.h" class HloControlFlowFlatteningTest : public HloTestBase { public: absl::StatusOr<std::unique_ptr<HloModule>> PartitionComputation( std::unique_ptr<VerifiedHloModule> hlo_module, int64_t num_devices = 2) { spmd::SpmdPartitionerOptions options; auto collective_ops_creator = spmd::GetDefaultCollectiveOpsCreator(num_devices, /*num_replicas=*/1); collective_ops_creator.create_cross_partition_all_gather = nullptr; HloModuleConfig config = GetModuleConfigForTest(); config.set_use_spmd_partitioning(true); config.set_num_partitions(num_devices); HloPassPipeline pass("spmd-partitioning"); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); pass.AddPass<spmd::SpmdPartitioner>(num_devices, /*num_replicas=*/1, options, collective_ops_creator); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); TF_RETURN_IF_ERROR(pass.Run(hlo_module.get()).status()); return absl::StatusOr<std::unique_ptr<HloModule>>(std::move(hlo_module)); } };
HloControlFlowFlatteningTest_CollectivePermuteInPlaceUpdate
xla/tools/hlo_control_flow_flattening_test.cc
HloInstruction* CreateConstant(const Shape& shape, HloComputation* computation) { if (shape.IsTuple()) { std::vector<HloInstruction*> tuple_arguments(shape.tuple_shapes_size()); for (int index = 0; index < shape.tuple_shapes_size(); ++index) { tuple_arguments[index] = CreateConstant(shape.tuple_shapes(index), computation); } return computation->AddInstruction( HloInstruction::CreateTuple(tuple_arguments)); } else { return computation->AddInstruction( HloInstruction::CreateConstant(Literal::CreateFromShape(shape))); } } void PrintSubexpression(HloInstruction* inst, int depth) { if (depth == 0) { return; } for (auto* operand : inst->operands()) { PrintSubexpression(operand, depth - 1); } VLOG(2) << inst->ToString(); } VLOG(2) << inst->ToString(); bool IsConstantScalarInt(const HloInstruction* inst) { return inst->opcode() == HloOpcode::kConstant && ShapeUtil::IsEffectiveScalar(inst->shape()) && inst->shape().IsInteger(); } bool IsNotContainedInLoop(const HloInstruction& while_hlo, const CallGraph& call_graph) { const HloComputation* computation = while_hlo.parent(); while (!computation->IsEntryComputation()) { auto& node = call_graph.GetNode(computation); CHECK_EQ(node.caller_callsites().size(), 1) << "The module is not flattened!"; auto& callsite = node.caller_callsites()[0]; if (callsite.instruction()->opcode() == HloOpcode::kWhile) { // Another while loop has been found traversing up the call tree. return false; } computation = callsite.instruction()->parent(); } // No calling while loops were found. return true; } int GetLoopBound(const HloInstruction& while_hlo, const int default_loop_count, const int max_loop_count) { HloInstruction* condition = while_hlo.while_condition()->root_instruction(); if (condition->opcode() == HloOpcode::kCompare) { int64_t value = 0; Comparison::Direction cmp = condition->comparison_direction(); if ((cmp == Comparison::Direction::kLt || cmp == Comparison::Direction::kLe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(1))) { value = *condition->operand(1)->literal().GetFirstInteger(); } else if ((cmp == Comparison::Direction::kGt || cmp == Comparison::Direction::kGe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(0))) { value = *condition->operand(0)->literal().GetFirstInteger(); } if (value > 0) { // Caps to a max loop count to avoid long execution times. return std::min(value, static_cast<int64_t>(max_loop_count)); } } return default_loop_count; } int GetLoopBoundWithOuterLoopMax(const HloInstruction& while_hlo, const CallGraph& call_graph, const int default_loop_count, const int max_outer_loop_count, const int max_loop_count) { int loop_bound = GetLoopBound(while_hlo, default_loop_count, max_loop_count); if (loop_bound > max_outer_loop_count) { // First does the inexpensive loop bound check to avoid as many // expensive graph traversals in IsNotContainedInLoop as possible. if (IsNotContainedInLoop(while_hlo, call_graph)) { return max_outer_loop_count; } } return loop_bound; } absl::Status HloControlFlowFlattening::FlattenWhileLoop( HloInstruction* while_hlo, const CallGraph& call_graph) const { CHECK_EQ(while_hlo->opcode(), HloOpcode::kWhile); HloComputation* computation = while_hlo->parent(); // Add a new induction variable. HloInstruction* initialization = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(0))); // Create a new while operand with the induction variable added. HloInstruction* old_tuple = while_hlo->mutable_operand(0); HloInstruction* new_tuple = TupleUtil::AppendSuffix(old_tuple, {initialization}); int new_tuple_size = new_tuple->shape().tuple_shapes().size(); TF_RETURN_IF_ERROR(while_hlo->ReplaceOperandWithDifferentShape(0, new_tuple)); auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; // Replace the given tuple-shaped instruction of size N in each of its // non-get-tuple-element users with a new tuple instruction which has the // first N - 1 elements. auto replace_non_gte_users = [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; { // Add the new variable to the while loop condition. HloComputation* condition = while_hlo->while_condition(); TF_RETURN_IF_ERROR(change_op_shape(condition->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(condition->parameter_instruction(0)).status()); if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); PrintSubexpression(condition->root_instruction(), /*depth=*/3); } const int loop_bound = GetLoopBoundWithOuterLoopMax( *while_hlo, call_graph, while_execution_count_, max_outer_loop_count_, max_loop_count_); VLOG(1) << "loop_bound = " << loop_bound; HloInstruction* limit = condition->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(loop_bound))); Shape shape = initialization->shape(); HloInstruction* induction_variable = condition->AddInstruction(HloInstruction::CreateGetTupleElement( shape, condition->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* compare = condition->AddInstruction(HloInstruction::CreateCompare( ShapeUtil::MakeShape(PRED, {}), induction_variable, limit, ComparisonDirection::kLt)); TF_RETURN_IF_ERROR( condition->ReplaceInstruction(condition->root_instruction(), compare)); } { // Add the new variable to the while loop body. HloComputation* body = while_hlo->while_body(); TF_RETURN_IF_ERROR(change_op_shape(body->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(body->parameter_instruction(0)).status()); HloInstruction* old_root = body->root_instruction(); Shape shape = initialization->shape(); HloInstruction* induction_variable = body->AddInstruction(HloInstruction::CreateGetTupleElement( shape, body->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* increment = body->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(1))); induction_variable = body->AddInstruction(HloInstruction::CreateBinary( shape, HloOpcode::kAdd, induction_variable, increment)); HloInstruction* new_root = TupleUtil::AppendSuffix(old_root, {induction_variable}); body->set_root_instruction(new_root, /*accept_different_shape=*/true); } // Snapshot the users of while hlo before we add new users. std::vector<HloInstruction*> while_users(while_hlo->users().begin(), while_hlo->users().end()); // Take care of the users of this while loop. TF_RETURN_IF_ERROR(change_op_shape(while_hlo)); TF_ASSIGN_OR_RETURN(HloInstruction * prefix, replace_non_gte_users(while_hlo)); // If the while loop had been the root of its computation, make the prefix new // root. if (while_hlo->parent()->root_instruction() == while_hlo) { // We need to set accept_different_shape=true to reset the root shape to the // original, because we have already changed the shape of the old root // (while). if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix(while_hlo, new_tuple_size - 1); } while_hlo->parent()->set_root_instruction(prefix, /*accept_different_shape=*/true); } return absl::OkStatus(); } auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); VLOG(1) << "loop_bound = " << loop_bound; absl::Status HloControlFlowFlattening::RemoveInfeed( HloInstruction* infeed_hlo) const { CHECK_EQ(infeed_hlo->opcode(), HloOpcode::kInfeed); HloComputation* computation = infeed_hlo->parent(); CHECK_EQ(infeed_hlo->shape().tuple_shapes_size(), 2); const Shape& infeed_shape = ShapeUtil::GetSubshape(infeed_hlo->shape(), {0}); HloInstruction* custom_call = computation->AddInstruction( HloInstruction::CreateCustomCall(infeed_shape, {}, kNopCustomCallTarget)); // Create a new tuple consisting of the constant and the token that was // originally the operand of infeed, and replace the infeed operation. auto new_tuple = HloInstruction::CreateTuple( {custom_call, infeed_hlo->mutable_operand(0)}); TF_RETURN_IF_ERROR( computation->ReplaceWithNewInstruction(infeed_hlo, std::move(new_tuple))); custom_call->SetAndSanitizeName(infeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveRecvAndRecvDone( HloInstruction* recv_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(recv_done->opcode(), HloOpcode::kRecvDone); CHECK_EQ(recv_done->operand_count(), 1); HloInstruction* recv = recv_done->mutable_operand(0); CHECK_EQ(recv->opcode(), HloOpcode::kRecv); HloComputation* computation = recv_done->parent(); CHECK_EQ(recv_done->shape().tuple_shapes_size(), 2); HloModule* module = computation->parent(); HloInstruction* custom_call_recv = computation->AddInstruction(HloInstruction::CreateCustomCall( recv->shape(), recv->operands(), kNopCustomCallTarget)); std::string original_recv_name(recv->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv, custom_call_recv); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(recv, custom_call_recv)); custom_call_recv->SetAndSanitizeName(original_recv_name); std::string original_recv_done_name(recv_done->name()); HloInstruction* custom_call_recv_done = computation->AddInstruction( HloInstruction::CreateCustomCall( recv_done->shape(), recv_done->operands(), kNopCustomCallTarget), recv_done->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv_done, custom_call_recv_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(recv_done, custom_call_recv_done)); custom_call_recv_done->SetAndSanitizeName(original_recv_done_name); return std::make_pair(custom_call_recv, custom_call_recv_done); } absl::Status HloControlFlowFlattening::RemoveOutfeed( HloInstruction* outfeed_hlo) const { CHECK_EQ(outfeed_hlo->opcode(), HloOpcode::kOutfeed); HloComputation* computation = outfeed_hlo->parent(); // Replace the outfeed with a no-op custom call with side effect to ensure the // operands aren't DCE'd. HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( outfeed_hlo->shape(), outfeed_hlo->operands(), kNopReturnTokenCustomCallTarget)); Cast<HloCustomCallInstruction>(custom_call) ->set_custom_call_has_side_effect(true); // For SPMD graphs, partitioner requires that side-effecting custom calls have // a sharding that is non-replicated. custom_call->set_sharding(HloSharding::Manual()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(outfeed_hlo, custom_call)); custom_call->SetAndSanitizeName(outfeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveSendAndSendDone( HloInstruction* send_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(send_done->opcode(), HloOpcode::kSendDone); CHECK_EQ(send_done->operand_count(), 1); HloInstruction* send = send_done->mutable_operand(0); CHECK_EQ(send->opcode(), HloOpcode::kSend); HloComputation* computation = send_done->parent(); HloModule* module = computation->parent(); HloInstruction* custom_call_send = computation->AddInstruction(HloInstruction::CreateCustomCall( send->shape(), send->operands(), kNopCustomCallTarget)); std::string original_send_name(send->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send, custom_call_send); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(send, custom_call_send)); custom_call_send->SetAndSanitizeName(original_send_name); HloInstruction* custom_call_send_done = computation->AddInstruction(HloInstruction::CreateCustomCall( send_done->shape(), send_done->operands(), kNopReturnTokenCustomCallTarget)); std::string original_send_done_name(send_done->name()); Cast<HloCustomCallInstruction>(custom_call_send_done) ->set_custom_call_has_side_effect(true); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send_done, custom_call_send_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(send_done, custom_call_send_done)); custom_call_send_done->SetAndSanitizeName(original_send_done_name); return std::make_pair(custom_call_send, custom_call_send_done); } absl::StatusOr<HloInstruction*> HloControlFlowFlattening::RemoveCollective( HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( hlo->shape(), hlo->operands(), kNopCustomCallTarget)); // Copy backend config. This is necessary for a collective op in megacore // fusion. custom_call->CopyBackendConfigFrom(hlo); HloModule* module = computation->parent(); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, hlo, custom_call); } std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, custom_call)); custom_call->SetAndSanitizeName(original_op_name); return custom_call; } absl::Status HloControlFlowFlattening::RemoveId(HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* zero = CreateConstant(hlo->shape(), computation); std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, zero)); zero->SetAndSanitizeName(original_op_name); return absl::OkStatus(); } absl::StatusOr<bool> HloControlFlowFlattening::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { auto call_graph = CallGraph::Build(module); bool changed = false; absl::flat_hash_set<HloInstruction*> removed; for (HloComputation* computation : module->computations(execution_threads)) { // Do not change computations that are wrapped by async calls. Instead we // remove the async callers if needed. if (computation->IsAsyncComputation()) { continue; } for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (removed.contains(instruction)) { // Skip the instruction if it is already removed. continue; } if (flatten_while_loop_ && instruction->opcode() == HloOpcode::kWhile) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(FlattenWhileLoop(instruction, *call_graph)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kInfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveInfeed(instruction)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kOutfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveOutfeed(instruction)); changed = true; } else if (instruction->opcode() == HloOpcode::kSendDone) { auto send_done_instruction = DynCast<HloSendDoneInstruction>(instruction); CHECK(send_done_instruction); if (remove_comm_ || (remove_host_transfer_ && send_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveSendAndSendDone(instruction, &removed).status()); changed = true; } } else if (instruction->opcode() == HloOpcode::kRecvDone) { auto recv_done_instruction = DynCast<HloRecvDoneInstruction>(instruction); CHECK(recv_done_instruction); if (remove_comm_ || (remove_host_transfer_ && recv_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveRecvAndRecvDone(instruction, &removed).status()); changed = true; } } else if (remove_comm_ && IsCollective(instruction) && !instruction->parent()->IsFusionComputation() && (instruction->opcode() != HloOpcode::kAsyncStart && instruction->opcode() != HloOpcode::kAsyncUpdate)) { // We do not remove kAsyncStart or kAsyncUpdate here since we expect // them to be removed as a part of the async chain above. // We should remove the async chain all together because the async // wrapped computation is only associated with the AsyncStart. So we // need to refer to the AsyncStart in order to determine whether // the Done or the Update wraps a collective. if (instruction->opcode() == HloOpcode::kAsyncDone) { while (instruction->opcode() == HloOpcode::kAsyncDone || instruction->opcode() == HloOpcode::kAsyncUpdate || instruction->opcode() == HloOpcode::kAsyncStart) { HloInstruction* operand = instruction->mutable_operand(0); VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); instruction = operand; } } else { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); } changed = true; } else if (remove_comm_ && (instruction->opcode() == HloOpcode::kPartitionId || instruction->opcode() == HloOpcode::kReplicaId || (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == "SliceId"))) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveId(instruction)); changed = true; } } } HloDCE hlo_dce; TF_ASSIGN_OR_RETURN(bool dce_changed, hlo_dce.Run(module, execution_threads)); changed |= dce_changed; // Fix the schedule if the module was scheduled. if (changed && module->has_schedule()) { TF_RETURN_IF_ERROR(module->schedule().Update()); } XLA_VLOG_LINES(3, module->ToString()); return changed; } VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); XLA_VLOG_LINES(3, module->ToString());
#include "xla/tools/hlo_control_flow_flattening.h" #include <memory> #include <utility> #include "absl/strings/str_replace.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/collective_ops_utils.h" #include "xla/service/despecializer.h" #include "xla/service/hlo_verifier.h" #include "xla/service/spmd/spmd_partitioner.h" #include "xla/tests/hlo_test_base.h" #include "tsl/lib/core/status_test_util.h" class HloControlFlowFlatteningTest : public HloTestBase { public: absl::StatusOr<std::unique_ptr<HloModule>> PartitionComputation( std::unique_ptr<VerifiedHloModule> hlo_module, int64_t num_devices = 2) { spmd::SpmdPartitionerOptions options; auto collective_ops_creator = spmd::GetDefaultCollectiveOpsCreator(num_devices, /*num_replicas=*/1); collective_ops_creator.create_cross_partition_all_gather = nullptr; HloModuleConfig config = GetModuleConfigForTest(); config.set_use_spmd_partitioning(true); config.set_num_partitions(num_devices); HloPassPipeline pass("spmd-partitioning"); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); pass.AddPass<spmd::SpmdPartitioner>(num_devices, /*num_replicas=*/1, options, collective_ops_creator); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); TF_RETURN_IF_ERROR(pass.Run(hlo_module.get()).status()); return absl::StatusOr<std::unique_ptr<HloModule>>(std::move(hlo_module)); } };
HloControlFlowFlatteningTest_CollectivePermuteStartAndDone
xla/tools/hlo_control_flow_flattening_test.cc
HloInstruction* CreateConstant(const Shape& shape, HloComputation* computation) { if (shape.IsTuple()) { std::vector<HloInstruction*> tuple_arguments(shape.tuple_shapes_size()); for (int index = 0; index < shape.tuple_shapes_size(); ++index) { tuple_arguments[index] = CreateConstant(shape.tuple_shapes(index), computation); } return computation->AddInstruction( HloInstruction::CreateTuple(tuple_arguments)); } else { return computation->AddInstruction( HloInstruction::CreateConstant(Literal::CreateFromShape(shape))); } } void PrintSubexpression(HloInstruction* inst, int depth) { if (depth == 0) { return; } for (auto* operand : inst->operands()) { PrintSubexpression(operand, depth - 1); } VLOG(2) << inst->ToString(); } VLOG(2) << inst->ToString(); bool IsConstantScalarInt(const HloInstruction* inst) { return inst->opcode() == HloOpcode::kConstant && ShapeUtil::IsEffectiveScalar(inst->shape()) && inst->shape().IsInteger(); } bool IsNotContainedInLoop(const HloInstruction& while_hlo, const CallGraph& call_graph) { const HloComputation* computation = while_hlo.parent(); while (!computation->IsEntryComputation()) { auto& node = call_graph.GetNode(computation); CHECK_EQ(node.caller_callsites().size(), 1) << "The module is not flattened!"; auto& callsite = node.caller_callsites()[0]; if (callsite.instruction()->opcode() == HloOpcode::kWhile) { // Another while loop has been found traversing up the call tree. return false; } computation = callsite.instruction()->parent(); } // No calling while loops were found. return true; } int GetLoopBound(const HloInstruction& while_hlo, const int default_loop_count, const int max_loop_count) { HloInstruction* condition = while_hlo.while_condition()->root_instruction(); if (condition->opcode() == HloOpcode::kCompare) { int64_t value = 0; Comparison::Direction cmp = condition->comparison_direction(); if ((cmp == Comparison::Direction::kLt || cmp == Comparison::Direction::kLe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(1))) { value = *condition->operand(1)->literal().GetFirstInteger(); } else if ((cmp == Comparison::Direction::kGt || cmp == Comparison::Direction::kGe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(0))) { value = *condition->operand(0)->literal().GetFirstInteger(); } if (value > 0) { // Caps to a max loop count to avoid long execution times. return std::min(value, static_cast<int64_t>(max_loop_count)); } } return default_loop_count; } int GetLoopBoundWithOuterLoopMax(const HloInstruction& while_hlo, const CallGraph& call_graph, const int default_loop_count, const int max_outer_loop_count, const int max_loop_count) { int loop_bound = GetLoopBound(while_hlo, default_loop_count, max_loop_count); if (loop_bound > max_outer_loop_count) { // First does the inexpensive loop bound check to avoid as many // expensive graph traversals in IsNotContainedInLoop as possible. if (IsNotContainedInLoop(while_hlo, call_graph)) { return max_outer_loop_count; } } return loop_bound; } absl::Status HloControlFlowFlattening::FlattenWhileLoop( HloInstruction* while_hlo, const CallGraph& call_graph) const { CHECK_EQ(while_hlo->opcode(), HloOpcode::kWhile); HloComputation* computation = while_hlo->parent(); // Add a new induction variable. HloInstruction* initialization = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(0))); // Create a new while operand with the induction variable added. HloInstruction* old_tuple = while_hlo->mutable_operand(0); HloInstruction* new_tuple = TupleUtil::AppendSuffix(old_tuple, {initialization}); int new_tuple_size = new_tuple->shape().tuple_shapes().size(); TF_RETURN_IF_ERROR(while_hlo->ReplaceOperandWithDifferentShape(0, new_tuple)); auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; // Replace the given tuple-shaped instruction of size N in each of its // non-get-tuple-element users with a new tuple instruction which has the // first N - 1 elements. auto replace_non_gte_users = [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; { // Add the new variable to the while loop condition. HloComputation* condition = while_hlo->while_condition(); TF_RETURN_IF_ERROR(change_op_shape(condition->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(condition->parameter_instruction(0)).status()); if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); PrintSubexpression(condition->root_instruction(), /*depth=*/3); } const int loop_bound = GetLoopBoundWithOuterLoopMax( *while_hlo, call_graph, while_execution_count_, max_outer_loop_count_, max_loop_count_); VLOG(1) << "loop_bound = " << loop_bound; HloInstruction* limit = condition->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(loop_bound))); Shape shape = initialization->shape(); HloInstruction* induction_variable = condition->AddInstruction(HloInstruction::CreateGetTupleElement( shape, condition->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* compare = condition->AddInstruction(HloInstruction::CreateCompare( ShapeUtil::MakeShape(PRED, {}), induction_variable, limit, ComparisonDirection::kLt)); TF_RETURN_IF_ERROR( condition->ReplaceInstruction(condition->root_instruction(), compare)); } { // Add the new variable to the while loop body. HloComputation* body = while_hlo->while_body(); TF_RETURN_IF_ERROR(change_op_shape(body->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(body->parameter_instruction(0)).status()); HloInstruction* old_root = body->root_instruction(); Shape shape = initialization->shape(); HloInstruction* induction_variable = body->AddInstruction(HloInstruction::CreateGetTupleElement( shape, body->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* increment = body->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(1))); induction_variable = body->AddInstruction(HloInstruction::CreateBinary( shape, HloOpcode::kAdd, induction_variable, increment)); HloInstruction* new_root = TupleUtil::AppendSuffix(old_root, {induction_variable}); body->set_root_instruction(new_root, /*accept_different_shape=*/true); } // Snapshot the users of while hlo before we add new users. std::vector<HloInstruction*> while_users(while_hlo->users().begin(), while_hlo->users().end()); // Take care of the users of this while loop. TF_RETURN_IF_ERROR(change_op_shape(while_hlo)); TF_ASSIGN_OR_RETURN(HloInstruction * prefix, replace_non_gte_users(while_hlo)); // If the while loop had been the root of its computation, make the prefix new // root. if (while_hlo->parent()->root_instruction() == while_hlo) { // We need to set accept_different_shape=true to reset the root shape to the // original, because we have already changed the shape of the old root // (while). if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix(while_hlo, new_tuple_size - 1); } while_hlo->parent()->set_root_instruction(prefix, /*accept_different_shape=*/true); } return absl::OkStatus(); } auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); VLOG(1) << "loop_bound = " << loop_bound; absl::Status HloControlFlowFlattening::RemoveInfeed( HloInstruction* infeed_hlo) const { CHECK_EQ(infeed_hlo->opcode(), HloOpcode::kInfeed); HloComputation* computation = infeed_hlo->parent(); CHECK_EQ(infeed_hlo->shape().tuple_shapes_size(), 2); const Shape& infeed_shape = ShapeUtil::GetSubshape(infeed_hlo->shape(), {0}); HloInstruction* custom_call = computation->AddInstruction( HloInstruction::CreateCustomCall(infeed_shape, {}, kNopCustomCallTarget)); // Create a new tuple consisting of the constant and the token that was // originally the operand of infeed, and replace the infeed operation. auto new_tuple = HloInstruction::CreateTuple( {custom_call, infeed_hlo->mutable_operand(0)}); TF_RETURN_IF_ERROR( computation->ReplaceWithNewInstruction(infeed_hlo, std::move(new_tuple))); custom_call->SetAndSanitizeName(infeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveRecvAndRecvDone( HloInstruction* recv_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(recv_done->opcode(), HloOpcode::kRecvDone); CHECK_EQ(recv_done->operand_count(), 1); HloInstruction* recv = recv_done->mutable_operand(0); CHECK_EQ(recv->opcode(), HloOpcode::kRecv); HloComputation* computation = recv_done->parent(); CHECK_EQ(recv_done->shape().tuple_shapes_size(), 2); HloModule* module = computation->parent(); HloInstruction* custom_call_recv = computation->AddInstruction(HloInstruction::CreateCustomCall( recv->shape(), recv->operands(), kNopCustomCallTarget)); std::string original_recv_name(recv->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv, custom_call_recv); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(recv, custom_call_recv)); custom_call_recv->SetAndSanitizeName(original_recv_name); std::string original_recv_done_name(recv_done->name()); HloInstruction* custom_call_recv_done = computation->AddInstruction( HloInstruction::CreateCustomCall( recv_done->shape(), recv_done->operands(), kNopCustomCallTarget), recv_done->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv_done, custom_call_recv_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(recv_done, custom_call_recv_done)); custom_call_recv_done->SetAndSanitizeName(original_recv_done_name); return std::make_pair(custom_call_recv, custom_call_recv_done); } absl::Status HloControlFlowFlattening::RemoveOutfeed( HloInstruction* outfeed_hlo) const { CHECK_EQ(outfeed_hlo->opcode(), HloOpcode::kOutfeed); HloComputation* computation = outfeed_hlo->parent(); // Replace the outfeed with a no-op custom call with side effect to ensure the // operands aren't DCE'd. HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( outfeed_hlo->shape(), outfeed_hlo->operands(), kNopReturnTokenCustomCallTarget)); Cast<HloCustomCallInstruction>(custom_call) ->set_custom_call_has_side_effect(true); // For SPMD graphs, partitioner requires that side-effecting custom calls have // a sharding that is non-replicated. custom_call->set_sharding(HloSharding::Manual()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(outfeed_hlo, custom_call)); custom_call->SetAndSanitizeName(outfeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveSendAndSendDone( HloInstruction* send_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(send_done->opcode(), HloOpcode::kSendDone); CHECK_EQ(send_done->operand_count(), 1); HloInstruction* send = send_done->mutable_operand(0); CHECK_EQ(send->opcode(), HloOpcode::kSend); HloComputation* computation = send_done->parent(); HloModule* module = computation->parent(); HloInstruction* custom_call_send = computation->AddInstruction(HloInstruction::CreateCustomCall( send->shape(), send->operands(), kNopCustomCallTarget)); std::string original_send_name(send->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send, custom_call_send); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(send, custom_call_send)); custom_call_send->SetAndSanitizeName(original_send_name); HloInstruction* custom_call_send_done = computation->AddInstruction(HloInstruction::CreateCustomCall( send_done->shape(), send_done->operands(), kNopReturnTokenCustomCallTarget)); std::string original_send_done_name(send_done->name()); Cast<HloCustomCallInstruction>(custom_call_send_done) ->set_custom_call_has_side_effect(true); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send_done, custom_call_send_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(send_done, custom_call_send_done)); custom_call_send_done->SetAndSanitizeName(original_send_done_name); return std::make_pair(custom_call_send, custom_call_send_done); } absl::StatusOr<HloInstruction*> HloControlFlowFlattening::RemoveCollective( HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( hlo->shape(), hlo->operands(), kNopCustomCallTarget)); // Copy backend config. This is necessary for a collective op in megacore // fusion. custom_call->CopyBackendConfigFrom(hlo); HloModule* module = computation->parent(); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, hlo, custom_call); } std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, custom_call)); custom_call->SetAndSanitizeName(original_op_name); return custom_call; } absl::Status HloControlFlowFlattening::RemoveId(HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* zero = CreateConstant(hlo->shape(), computation); std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, zero)); zero->SetAndSanitizeName(original_op_name); return absl::OkStatus(); } absl::StatusOr<bool> HloControlFlowFlattening::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { auto call_graph = CallGraph::Build(module); bool changed = false; absl::flat_hash_set<HloInstruction*> removed; for (HloComputation* computation : module->computations(execution_threads)) { // Do not change computations that are wrapped by async calls. Instead we // remove the async callers if needed. if (computation->IsAsyncComputation()) { continue; } for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (removed.contains(instruction)) { // Skip the instruction if it is already removed. continue; } if (flatten_while_loop_ && instruction->opcode() == HloOpcode::kWhile) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(FlattenWhileLoop(instruction, *call_graph)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kInfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveInfeed(instruction)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kOutfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveOutfeed(instruction)); changed = true; } else if (instruction->opcode() == HloOpcode::kSendDone) { auto send_done_instruction = DynCast<HloSendDoneInstruction>(instruction); CHECK(send_done_instruction); if (remove_comm_ || (remove_host_transfer_ && send_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveSendAndSendDone(instruction, &removed).status()); changed = true; } } else if (instruction->opcode() == HloOpcode::kRecvDone) { auto recv_done_instruction = DynCast<HloRecvDoneInstruction>(instruction); CHECK(recv_done_instruction); if (remove_comm_ || (remove_host_transfer_ && recv_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveRecvAndRecvDone(instruction, &removed).status()); changed = true; } } else if (remove_comm_ && IsCollective(instruction) && !instruction->parent()->IsFusionComputation() && (instruction->opcode() != HloOpcode::kAsyncStart && instruction->opcode() != HloOpcode::kAsyncUpdate)) { // We do not remove kAsyncStart or kAsyncUpdate here since we expect // them to be removed as a part of the async chain above. // We should remove the async chain all together because the async // wrapped computation is only associated with the AsyncStart. So we // need to refer to the AsyncStart in order to determine whether // the Done or the Update wraps a collective. if (instruction->opcode() == HloOpcode::kAsyncDone) { while (instruction->opcode() == HloOpcode::kAsyncDone || instruction->opcode() == HloOpcode::kAsyncUpdate || instruction->opcode() == HloOpcode::kAsyncStart) { HloInstruction* operand = instruction->mutable_operand(0); VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); instruction = operand; } } else { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); } changed = true; } else if (remove_comm_ && (instruction->opcode() == HloOpcode::kPartitionId || instruction->opcode() == HloOpcode::kReplicaId || (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == "SliceId"))) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveId(instruction)); changed = true; } } } HloDCE hlo_dce; TF_ASSIGN_OR_RETURN(bool dce_changed, hlo_dce.Run(module, execution_threads)); changed |= dce_changed; // Fix the schedule if the module was scheduled. if (changed && module->has_schedule()) { TF_RETURN_IF_ERROR(module->schedule().Update()); } XLA_VLOG_LINES(3, module->ToString()); return changed; } VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); XLA_VLOG_LINES(3, module->ToString());
#include "xla/tools/hlo_control_flow_flattening.h" #include <memory> #include <utility> #include "absl/strings/str_replace.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/collective_ops_utils.h" #include "xla/service/despecializer.h" #include "xla/service/hlo_verifier.h" #include "xla/service/spmd/spmd_partitioner.h" #include "xla/tests/hlo_test_base.h" #include "tsl/lib/core/status_test_util.h" class HloControlFlowFlatteningTest : public HloTestBase { public: absl::StatusOr<std::unique_ptr<HloModule>> PartitionComputation( std::unique_ptr<VerifiedHloModule> hlo_module, int64_t num_devices = 2) { spmd::SpmdPartitionerOptions options; auto collective_ops_creator = spmd::GetDefaultCollectiveOpsCreator(num_devices, /*num_replicas=*/1); collective_ops_creator.create_cross_partition_all_gather = nullptr; HloModuleConfig config = GetModuleConfigForTest(); config.set_use_spmd_partitioning(true); config.set_num_partitions(num_devices); HloPassPipeline pass("spmd-partitioning"); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); pass.AddPass<spmd::SpmdPartitioner>(num_devices, /*num_replicas=*/1, options, collective_ops_creator); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); TF_RETURN_IF_ERROR(pass.Run(hlo_module.get()).status()); return absl::StatusOr<std::unique_ptr<HloModule>>(std::move(hlo_module)); } };
HloControlFlowFlatteningTest_Infeed
xla/tools/hlo_control_flow_flattening_test.cc
HloInstruction* CreateConstant(const Shape& shape, HloComputation* computation) { if (shape.IsTuple()) { std::vector<HloInstruction*> tuple_arguments(shape.tuple_shapes_size()); for (int index = 0; index < shape.tuple_shapes_size(); ++index) { tuple_arguments[index] = CreateConstant(shape.tuple_shapes(index), computation); } return computation->AddInstruction( HloInstruction::CreateTuple(tuple_arguments)); } else { return computation->AddInstruction( HloInstruction::CreateConstant(Literal::CreateFromShape(shape))); } } void PrintSubexpression(HloInstruction* inst, int depth) { if (depth == 0) { return; } for (auto* operand : inst->operands()) { PrintSubexpression(operand, depth - 1); } VLOG(2) << inst->ToString(); } VLOG(2) << inst->ToString(); bool IsConstantScalarInt(const HloInstruction* inst) { return inst->opcode() == HloOpcode::kConstant && ShapeUtil::IsEffectiveScalar(inst->shape()) && inst->shape().IsInteger(); } bool IsNotContainedInLoop(const HloInstruction& while_hlo, const CallGraph& call_graph) { const HloComputation* computation = while_hlo.parent(); while (!computation->IsEntryComputation()) { auto& node = call_graph.GetNode(computation); CHECK_EQ(node.caller_callsites().size(), 1) << "The module is not flattened!"; auto& callsite = node.caller_callsites()[0]; if (callsite.instruction()->opcode() == HloOpcode::kWhile) { // Another while loop has been found traversing up the call tree. return false; } computation = callsite.instruction()->parent(); } // No calling while loops were found. return true; } int GetLoopBound(const HloInstruction& while_hlo, const int default_loop_count, const int max_loop_count) { HloInstruction* condition = while_hlo.while_condition()->root_instruction(); if (condition->opcode() == HloOpcode::kCompare) { int64_t value = 0; Comparison::Direction cmp = condition->comparison_direction(); if ((cmp == Comparison::Direction::kLt || cmp == Comparison::Direction::kLe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(1))) { value = *condition->operand(1)->literal().GetFirstInteger(); } else if ((cmp == Comparison::Direction::kGt || cmp == Comparison::Direction::kGe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(0))) { value = *condition->operand(0)->literal().GetFirstInteger(); } if (value > 0) { // Caps to a max loop count to avoid long execution times. return std::min(value, static_cast<int64_t>(max_loop_count)); } } return default_loop_count; } int GetLoopBoundWithOuterLoopMax(const HloInstruction& while_hlo, const CallGraph& call_graph, const int default_loop_count, const int max_outer_loop_count, const int max_loop_count) { int loop_bound = GetLoopBound(while_hlo, default_loop_count, max_loop_count); if (loop_bound > max_outer_loop_count) { // First does the inexpensive loop bound check to avoid as many // expensive graph traversals in IsNotContainedInLoop as possible. if (IsNotContainedInLoop(while_hlo, call_graph)) { return max_outer_loop_count; } } return loop_bound; } absl::Status HloControlFlowFlattening::FlattenWhileLoop( HloInstruction* while_hlo, const CallGraph& call_graph) const { CHECK_EQ(while_hlo->opcode(), HloOpcode::kWhile); HloComputation* computation = while_hlo->parent(); // Add a new induction variable. HloInstruction* initialization = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(0))); // Create a new while operand with the induction variable added. HloInstruction* old_tuple = while_hlo->mutable_operand(0); HloInstruction* new_tuple = TupleUtil::AppendSuffix(old_tuple, {initialization}); int new_tuple_size = new_tuple->shape().tuple_shapes().size(); TF_RETURN_IF_ERROR(while_hlo->ReplaceOperandWithDifferentShape(0, new_tuple)); auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; // Replace the given tuple-shaped instruction of size N in each of its // non-get-tuple-element users with a new tuple instruction which has the // first N - 1 elements. auto replace_non_gte_users = [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; { // Add the new variable to the while loop condition. HloComputation* condition = while_hlo->while_condition(); TF_RETURN_IF_ERROR(change_op_shape(condition->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(condition->parameter_instruction(0)).status()); if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); PrintSubexpression(condition->root_instruction(), /*depth=*/3); } const int loop_bound = GetLoopBoundWithOuterLoopMax( *while_hlo, call_graph, while_execution_count_, max_outer_loop_count_, max_loop_count_); VLOG(1) << "loop_bound = " << loop_bound; HloInstruction* limit = condition->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(loop_bound))); Shape shape = initialization->shape(); HloInstruction* induction_variable = condition->AddInstruction(HloInstruction::CreateGetTupleElement( shape, condition->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* compare = condition->AddInstruction(HloInstruction::CreateCompare( ShapeUtil::MakeShape(PRED, {}), induction_variable, limit, ComparisonDirection::kLt)); TF_RETURN_IF_ERROR( condition->ReplaceInstruction(condition->root_instruction(), compare)); } { // Add the new variable to the while loop body. HloComputation* body = while_hlo->while_body(); TF_RETURN_IF_ERROR(change_op_shape(body->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(body->parameter_instruction(0)).status()); HloInstruction* old_root = body->root_instruction(); Shape shape = initialization->shape(); HloInstruction* induction_variable = body->AddInstruction(HloInstruction::CreateGetTupleElement( shape, body->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* increment = body->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(1))); induction_variable = body->AddInstruction(HloInstruction::CreateBinary( shape, HloOpcode::kAdd, induction_variable, increment)); HloInstruction* new_root = TupleUtil::AppendSuffix(old_root, {induction_variable}); body->set_root_instruction(new_root, /*accept_different_shape=*/true); } // Snapshot the users of while hlo before we add new users. std::vector<HloInstruction*> while_users(while_hlo->users().begin(), while_hlo->users().end()); // Take care of the users of this while loop. TF_RETURN_IF_ERROR(change_op_shape(while_hlo)); TF_ASSIGN_OR_RETURN(HloInstruction * prefix, replace_non_gte_users(while_hlo)); // If the while loop had been the root of its computation, make the prefix new // root. if (while_hlo->parent()->root_instruction() == while_hlo) { // We need to set accept_different_shape=true to reset the root shape to the // original, because we have already changed the shape of the old root // (while). if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix(while_hlo, new_tuple_size - 1); } while_hlo->parent()->set_root_instruction(prefix, /*accept_different_shape=*/true); } return absl::OkStatus(); } auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); VLOG(1) << "loop_bound = " << loop_bound; absl::Status HloControlFlowFlattening::RemoveInfeed( HloInstruction* infeed_hlo) const { CHECK_EQ(infeed_hlo->opcode(), HloOpcode::kInfeed); HloComputation* computation = infeed_hlo->parent(); CHECK_EQ(infeed_hlo->shape().tuple_shapes_size(), 2); const Shape& infeed_shape = ShapeUtil::GetSubshape(infeed_hlo->shape(), {0}); HloInstruction* custom_call = computation->AddInstruction( HloInstruction::CreateCustomCall(infeed_shape, {}, kNopCustomCallTarget)); // Create a new tuple consisting of the constant and the token that was // originally the operand of infeed, and replace the infeed operation. auto new_tuple = HloInstruction::CreateTuple( {custom_call, infeed_hlo->mutable_operand(0)}); TF_RETURN_IF_ERROR( computation->ReplaceWithNewInstruction(infeed_hlo, std::move(new_tuple))); custom_call->SetAndSanitizeName(infeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveRecvAndRecvDone( HloInstruction* recv_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(recv_done->opcode(), HloOpcode::kRecvDone); CHECK_EQ(recv_done->operand_count(), 1); HloInstruction* recv = recv_done->mutable_operand(0); CHECK_EQ(recv->opcode(), HloOpcode::kRecv); HloComputation* computation = recv_done->parent(); CHECK_EQ(recv_done->shape().tuple_shapes_size(), 2); HloModule* module = computation->parent(); HloInstruction* custom_call_recv = computation->AddInstruction(HloInstruction::CreateCustomCall( recv->shape(), recv->operands(), kNopCustomCallTarget)); std::string original_recv_name(recv->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv, custom_call_recv); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(recv, custom_call_recv)); custom_call_recv->SetAndSanitizeName(original_recv_name); std::string original_recv_done_name(recv_done->name()); HloInstruction* custom_call_recv_done = computation->AddInstruction( HloInstruction::CreateCustomCall( recv_done->shape(), recv_done->operands(), kNopCustomCallTarget), recv_done->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv_done, custom_call_recv_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(recv_done, custom_call_recv_done)); custom_call_recv_done->SetAndSanitizeName(original_recv_done_name); return std::make_pair(custom_call_recv, custom_call_recv_done); } absl::Status HloControlFlowFlattening::RemoveOutfeed( HloInstruction* outfeed_hlo) const { CHECK_EQ(outfeed_hlo->opcode(), HloOpcode::kOutfeed); HloComputation* computation = outfeed_hlo->parent(); // Replace the outfeed with a no-op custom call with side effect to ensure the // operands aren't DCE'd. HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( outfeed_hlo->shape(), outfeed_hlo->operands(), kNopReturnTokenCustomCallTarget)); Cast<HloCustomCallInstruction>(custom_call) ->set_custom_call_has_side_effect(true); // For SPMD graphs, partitioner requires that side-effecting custom calls have // a sharding that is non-replicated. custom_call->set_sharding(HloSharding::Manual()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(outfeed_hlo, custom_call)); custom_call->SetAndSanitizeName(outfeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveSendAndSendDone( HloInstruction* send_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(send_done->opcode(), HloOpcode::kSendDone); CHECK_EQ(send_done->operand_count(), 1); HloInstruction* send = send_done->mutable_operand(0); CHECK_EQ(send->opcode(), HloOpcode::kSend); HloComputation* computation = send_done->parent(); HloModule* module = computation->parent(); HloInstruction* custom_call_send = computation->AddInstruction(HloInstruction::CreateCustomCall( send->shape(), send->operands(), kNopCustomCallTarget)); std::string original_send_name(send->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send, custom_call_send); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(send, custom_call_send)); custom_call_send->SetAndSanitizeName(original_send_name); HloInstruction* custom_call_send_done = computation->AddInstruction(HloInstruction::CreateCustomCall( send_done->shape(), send_done->operands(), kNopReturnTokenCustomCallTarget)); std::string original_send_done_name(send_done->name()); Cast<HloCustomCallInstruction>(custom_call_send_done) ->set_custom_call_has_side_effect(true); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send_done, custom_call_send_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(send_done, custom_call_send_done)); custom_call_send_done->SetAndSanitizeName(original_send_done_name); return std::make_pair(custom_call_send, custom_call_send_done); } absl::StatusOr<HloInstruction*> HloControlFlowFlattening::RemoveCollective( HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( hlo->shape(), hlo->operands(), kNopCustomCallTarget)); // Copy backend config. This is necessary for a collective op in megacore // fusion. custom_call->CopyBackendConfigFrom(hlo); HloModule* module = computation->parent(); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, hlo, custom_call); } std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, custom_call)); custom_call->SetAndSanitizeName(original_op_name); return custom_call; } absl::Status HloControlFlowFlattening::RemoveId(HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* zero = CreateConstant(hlo->shape(), computation); std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, zero)); zero->SetAndSanitizeName(original_op_name); return absl::OkStatus(); } absl::StatusOr<bool> HloControlFlowFlattening::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { auto call_graph = CallGraph::Build(module); bool changed = false; absl::flat_hash_set<HloInstruction*> removed; for (HloComputation* computation : module->computations(execution_threads)) { // Do not change computations that are wrapped by async calls. Instead we // remove the async callers if needed. if (computation->IsAsyncComputation()) { continue; } for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (removed.contains(instruction)) { // Skip the instruction if it is already removed. continue; } if (flatten_while_loop_ && instruction->opcode() == HloOpcode::kWhile) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(FlattenWhileLoop(instruction, *call_graph)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kInfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveInfeed(instruction)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kOutfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveOutfeed(instruction)); changed = true; } else if (instruction->opcode() == HloOpcode::kSendDone) { auto send_done_instruction = DynCast<HloSendDoneInstruction>(instruction); CHECK(send_done_instruction); if (remove_comm_ || (remove_host_transfer_ && send_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveSendAndSendDone(instruction, &removed).status()); changed = true; } } else if (instruction->opcode() == HloOpcode::kRecvDone) { auto recv_done_instruction = DynCast<HloRecvDoneInstruction>(instruction); CHECK(recv_done_instruction); if (remove_comm_ || (remove_host_transfer_ && recv_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveRecvAndRecvDone(instruction, &removed).status()); changed = true; } } else if (remove_comm_ && IsCollective(instruction) && !instruction->parent()->IsFusionComputation() && (instruction->opcode() != HloOpcode::kAsyncStart && instruction->opcode() != HloOpcode::kAsyncUpdate)) { // We do not remove kAsyncStart or kAsyncUpdate here since we expect // them to be removed as a part of the async chain above. // We should remove the async chain all together because the async // wrapped computation is only associated with the AsyncStart. So we // need to refer to the AsyncStart in order to determine whether // the Done or the Update wraps a collective. if (instruction->opcode() == HloOpcode::kAsyncDone) { while (instruction->opcode() == HloOpcode::kAsyncDone || instruction->opcode() == HloOpcode::kAsyncUpdate || instruction->opcode() == HloOpcode::kAsyncStart) { HloInstruction* operand = instruction->mutable_operand(0); VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); instruction = operand; } } else { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); } changed = true; } else if (remove_comm_ && (instruction->opcode() == HloOpcode::kPartitionId || instruction->opcode() == HloOpcode::kReplicaId || (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == "SliceId"))) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveId(instruction)); changed = true; } } } HloDCE hlo_dce; TF_ASSIGN_OR_RETURN(bool dce_changed, hlo_dce.Run(module, execution_threads)); changed |= dce_changed; // Fix the schedule if the module was scheduled. if (changed && module->has_schedule()) { TF_RETURN_IF_ERROR(module->schedule().Update()); } XLA_VLOG_LINES(3, module->ToString()); return changed; } VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); XLA_VLOG_LINES(3, module->ToString());
#include "xla/tools/hlo_control_flow_flattening.h" #include <memory> #include <utility> #include "absl/strings/str_replace.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/collective_ops_utils.h" #include "xla/service/despecializer.h" #include "xla/service/hlo_verifier.h" #include "xla/service/spmd/spmd_partitioner.h" #include "xla/tests/hlo_test_base.h" #include "tsl/lib/core/status_test_util.h" class HloControlFlowFlatteningTest : public HloTestBase { public: absl::StatusOr<std::unique_ptr<HloModule>> PartitionComputation( std::unique_ptr<VerifiedHloModule> hlo_module, int64_t num_devices = 2) { spmd::SpmdPartitionerOptions options; auto collective_ops_creator = spmd::GetDefaultCollectiveOpsCreator(num_devices, /*num_replicas=*/1); collective_ops_creator.create_cross_partition_all_gather = nullptr; HloModuleConfig config = GetModuleConfigForTest(); config.set_use_spmd_partitioning(true); config.set_num_partitions(num_devices); HloPassPipeline pass("spmd-partitioning"); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); pass.AddPass<spmd::SpmdPartitioner>(num_devices, /*num_replicas=*/1, options, collective_ops_creator); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); TF_RETURN_IF_ERROR(pass.Run(hlo_module.get()).status()); return absl::StatusOr<std::unique_ptr<HloModule>>(std::move(hlo_module)); } }; TEST_F(HloControlFlowFlatteningTest, Infeed) { absl::string_view hlo_string = R"( HloModule Infeed ENTRY Infeed { after-all = token[] after-all() ROOT infeed.23 = ((bf16[3]{0}, s32[12,5]{0,1}), token[]) infeed(after-all) } )"; TF_ASSERT_OK_AND_ASSIGN(auto module, ParseAndReturnVerifiedModule(hlo_string)); HloControlFlowFlattening flattening( HloControlFlowFlattening::Options{/*while_execution_count=*/3}); EXPECT_TRUE(flattening.Run(module.get()).value()); TF_ASSERT_OK(HloVerifier(/*layout_sensitive=*/true, /*allow_mixed_precision=*/true) .Run(module.get()) .status()); auto custom_call = module->entry_computation()->GetInstructionWithName("infeed.23"); EXPECT_THAT(custom_call, op::CustomCall()); auto tuple = module->entry_computation()->root_instruction(); EXPECT_THAT(tuple, op::Tuple(custom_call, op::AfterAll())); }
HloControlFlowFlatteningTest_InfeedPreserveLayout
xla/tools/hlo_control_flow_flattening_test.cc
HloInstruction* CreateConstant(const Shape& shape, HloComputation* computation) { if (shape.IsTuple()) { std::vector<HloInstruction*> tuple_arguments(shape.tuple_shapes_size()); for (int index = 0; index < shape.tuple_shapes_size(); ++index) { tuple_arguments[index] = CreateConstant(shape.tuple_shapes(index), computation); } return computation->AddInstruction( HloInstruction::CreateTuple(tuple_arguments)); } else { return computation->AddInstruction( HloInstruction::CreateConstant(Literal::CreateFromShape(shape))); } } void PrintSubexpression(HloInstruction* inst, int depth) { if (depth == 0) { return; } for (auto* operand : inst->operands()) { PrintSubexpression(operand, depth - 1); } VLOG(2) << inst->ToString(); } VLOG(2) << inst->ToString(); bool IsConstantScalarInt(const HloInstruction* inst) { return inst->opcode() == HloOpcode::kConstant && ShapeUtil::IsEffectiveScalar(inst->shape()) && inst->shape().IsInteger(); } bool IsNotContainedInLoop(const HloInstruction& while_hlo, const CallGraph& call_graph) { const HloComputation* computation = while_hlo.parent(); while (!computation->IsEntryComputation()) { auto& node = call_graph.GetNode(computation); CHECK_EQ(node.caller_callsites().size(), 1) << "The module is not flattened!"; auto& callsite = node.caller_callsites()[0]; if (callsite.instruction()->opcode() == HloOpcode::kWhile) { // Another while loop has been found traversing up the call tree. return false; } computation = callsite.instruction()->parent(); } // No calling while loops were found. return true; } int GetLoopBound(const HloInstruction& while_hlo, const int default_loop_count, const int max_loop_count) { HloInstruction* condition = while_hlo.while_condition()->root_instruction(); if (condition->opcode() == HloOpcode::kCompare) { int64_t value = 0; Comparison::Direction cmp = condition->comparison_direction(); if ((cmp == Comparison::Direction::kLt || cmp == Comparison::Direction::kLe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(1))) { value = *condition->operand(1)->literal().GetFirstInteger(); } else if ((cmp == Comparison::Direction::kGt || cmp == Comparison::Direction::kGe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(0))) { value = *condition->operand(0)->literal().GetFirstInteger(); } if (value > 0) { // Caps to a max loop count to avoid long execution times. return std::min(value, static_cast<int64_t>(max_loop_count)); } } return default_loop_count; } int GetLoopBoundWithOuterLoopMax(const HloInstruction& while_hlo, const CallGraph& call_graph, const int default_loop_count, const int max_outer_loop_count, const int max_loop_count) { int loop_bound = GetLoopBound(while_hlo, default_loop_count, max_loop_count); if (loop_bound > max_outer_loop_count) { // First does the inexpensive loop bound check to avoid as many // expensive graph traversals in IsNotContainedInLoop as possible. if (IsNotContainedInLoop(while_hlo, call_graph)) { return max_outer_loop_count; } } return loop_bound; } absl::Status HloControlFlowFlattening::FlattenWhileLoop( HloInstruction* while_hlo, const CallGraph& call_graph) const { CHECK_EQ(while_hlo->opcode(), HloOpcode::kWhile); HloComputation* computation = while_hlo->parent(); // Add a new induction variable. HloInstruction* initialization = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(0))); // Create a new while operand with the induction variable added. HloInstruction* old_tuple = while_hlo->mutable_operand(0); HloInstruction* new_tuple = TupleUtil::AppendSuffix(old_tuple, {initialization}); int new_tuple_size = new_tuple->shape().tuple_shapes().size(); TF_RETURN_IF_ERROR(while_hlo->ReplaceOperandWithDifferentShape(0, new_tuple)); auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; // Replace the given tuple-shaped instruction of size N in each of its // non-get-tuple-element users with a new tuple instruction which has the // first N - 1 elements. auto replace_non_gte_users = [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; { // Add the new variable to the while loop condition. HloComputation* condition = while_hlo->while_condition(); TF_RETURN_IF_ERROR(change_op_shape(condition->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(condition->parameter_instruction(0)).status()); if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); PrintSubexpression(condition->root_instruction(), /*depth=*/3); } const int loop_bound = GetLoopBoundWithOuterLoopMax( *while_hlo, call_graph, while_execution_count_, max_outer_loop_count_, max_loop_count_); VLOG(1) << "loop_bound = " << loop_bound; HloInstruction* limit = condition->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(loop_bound))); Shape shape = initialization->shape(); HloInstruction* induction_variable = condition->AddInstruction(HloInstruction::CreateGetTupleElement( shape, condition->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* compare = condition->AddInstruction(HloInstruction::CreateCompare( ShapeUtil::MakeShape(PRED, {}), induction_variable, limit, ComparisonDirection::kLt)); TF_RETURN_IF_ERROR( condition->ReplaceInstruction(condition->root_instruction(), compare)); } { // Add the new variable to the while loop body. HloComputation* body = while_hlo->while_body(); TF_RETURN_IF_ERROR(change_op_shape(body->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(body->parameter_instruction(0)).status()); HloInstruction* old_root = body->root_instruction(); Shape shape = initialization->shape(); HloInstruction* induction_variable = body->AddInstruction(HloInstruction::CreateGetTupleElement( shape, body->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* increment = body->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(1))); induction_variable = body->AddInstruction(HloInstruction::CreateBinary( shape, HloOpcode::kAdd, induction_variable, increment)); HloInstruction* new_root = TupleUtil::AppendSuffix(old_root, {induction_variable}); body->set_root_instruction(new_root, /*accept_different_shape=*/true); } // Snapshot the users of while hlo before we add new users. std::vector<HloInstruction*> while_users(while_hlo->users().begin(), while_hlo->users().end()); // Take care of the users of this while loop. TF_RETURN_IF_ERROR(change_op_shape(while_hlo)); TF_ASSIGN_OR_RETURN(HloInstruction * prefix, replace_non_gte_users(while_hlo)); // If the while loop had been the root of its computation, make the prefix new // root. if (while_hlo->parent()->root_instruction() == while_hlo) { // We need to set accept_different_shape=true to reset the root shape to the // original, because we have already changed the shape of the old root // (while). if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix(while_hlo, new_tuple_size - 1); } while_hlo->parent()->set_root_instruction(prefix, /*accept_different_shape=*/true); } return absl::OkStatus(); } auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); VLOG(1) << "loop_bound = " << loop_bound; absl::Status HloControlFlowFlattening::RemoveInfeed( HloInstruction* infeed_hlo) const { CHECK_EQ(infeed_hlo->opcode(), HloOpcode::kInfeed); HloComputation* computation = infeed_hlo->parent(); CHECK_EQ(infeed_hlo->shape().tuple_shapes_size(), 2); const Shape& infeed_shape = ShapeUtil::GetSubshape(infeed_hlo->shape(), {0}); HloInstruction* custom_call = computation->AddInstruction( HloInstruction::CreateCustomCall(infeed_shape, {}, kNopCustomCallTarget)); // Create a new tuple consisting of the constant and the token that was // originally the operand of infeed, and replace the infeed operation. auto new_tuple = HloInstruction::CreateTuple( {custom_call, infeed_hlo->mutable_operand(0)}); TF_RETURN_IF_ERROR( computation->ReplaceWithNewInstruction(infeed_hlo, std::move(new_tuple))); custom_call->SetAndSanitizeName(infeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveRecvAndRecvDone( HloInstruction* recv_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(recv_done->opcode(), HloOpcode::kRecvDone); CHECK_EQ(recv_done->operand_count(), 1); HloInstruction* recv = recv_done->mutable_operand(0); CHECK_EQ(recv->opcode(), HloOpcode::kRecv); HloComputation* computation = recv_done->parent(); CHECK_EQ(recv_done->shape().tuple_shapes_size(), 2); HloModule* module = computation->parent(); HloInstruction* custom_call_recv = computation->AddInstruction(HloInstruction::CreateCustomCall( recv->shape(), recv->operands(), kNopCustomCallTarget)); std::string original_recv_name(recv->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv, custom_call_recv); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(recv, custom_call_recv)); custom_call_recv->SetAndSanitizeName(original_recv_name); std::string original_recv_done_name(recv_done->name()); HloInstruction* custom_call_recv_done = computation->AddInstruction( HloInstruction::CreateCustomCall( recv_done->shape(), recv_done->operands(), kNopCustomCallTarget), recv_done->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv_done, custom_call_recv_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(recv_done, custom_call_recv_done)); custom_call_recv_done->SetAndSanitizeName(original_recv_done_name); return std::make_pair(custom_call_recv, custom_call_recv_done); } absl::Status HloControlFlowFlattening::RemoveOutfeed( HloInstruction* outfeed_hlo) const { CHECK_EQ(outfeed_hlo->opcode(), HloOpcode::kOutfeed); HloComputation* computation = outfeed_hlo->parent(); // Replace the outfeed with a no-op custom call with side effect to ensure the // operands aren't DCE'd. HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( outfeed_hlo->shape(), outfeed_hlo->operands(), kNopReturnTokenCustomCallTarget)); Cast<HloCustomCallInstruction>(custom_call) ->set_custom_call_has_side_effect(true); // For SPMD graphs, partitioner requires that side-effecting custom calls have // a sharding that is non-replicated. custom_call->set_sharding(HloSharding::Manual()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(outfeed_hlo, custom_call)); custom_call->SetAndSanitizeName(outfeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveSendAndSendDone( HloInstruction* send_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(send_done->opcode(), HloOpcode::kSendDone); CHECK_EQ(send_done->operand_count(), 1); HloInstruction* send = send_done->mutable_operand(0); CHECK_EQ(send->opcode(), HloOpcode::kSend); HloComputation* computation = send_done->parent(); HloModule* module = computation->parent(); HloInstruction* custom_call_send = computation->AddInstruction(HloInstruction::CreateCustomCall( send->shape(), send->operands(), kNopCustomCallTarget)); std::string original_send_name(send->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send, custom_call_send); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(send, custom_call_send)); custom_call_send->SetAndSanitizeName(original_send_name); HloInstruction* custom_call_send_done = computation->AddInstruction(HloInstruction::CreateCustomCall( send_done->shape(), send_done->operands(), kNopReturnTokenCustomCallTarget)); std::string original_send_done_name(send_done->name()); Cast<HloCustomCallInstruction>(custom_call_send_done) ->set_custom_call_has_side_effect(true); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send_done, custom_call_send_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(send_done, custom_call_send_done)); custom_call_send_done->SetAndSanitizeName(original_send_done_name); return std::make_pair(custom_call_send, custom_call_send_done); } absl::StatusOr<HloInstruction*> HloControlFlowFlattening::RemoveCollective( HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( hlo->shape(), hlo->operands(), kNopCustomCallTarget)); // Copy backend config. This is necessary for a collective op in megacore // fusion. custom_call->CopyBackendConfigFrom(hlo); HloModule* module = computation->parent(); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, hlo, custom_call); } std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, custom_call)); custom_call->SetAndSanitizeName(original_op_name); return custom_call; } absl::Status HloControlFlowFlattening::RemoveId(HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* zero = CreateConstant(hlo->shape(), computation); std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, zero)); zero->SetAndSanitizeName(original_op_name); return absl::OkStatus(); } absl::StatusOr<bool> HloControlFlowFlattening::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { auto call_graph = CallGraph::Build(module); bool changed = false; absl::flat_hash_set<HloInstruction*> removed; for (HloComputation* computation : module->computations(execution_threads)) { // Do not change computations that are wrapped by async calls. Instead we // remove the async callers if needed. if (computation->IsAsyncComputation()) { continue; } for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (removed.contains(instruction)) { // Skip the instruction if it is already removed. continue; } if (flatten_while_loop_ && instruction->opcode() == HloOpcode::kWhile) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(FlattenWhileLoop(instruction, *call_graph)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kInfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveInfeed(instruction)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kOutfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveOutfeed(instruction)); changed = true; } else if (instruction->opcode() == HloOpcode::kSendDone) { auto send_done_instruction = DynCast<HloSendDoneInstruction>(instruction); CHECK(send_done_instruction); if (remove_comm_ || (remove_host_transfer_ && send_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveSendAndSendDone(instruction, &removed).status()); changed = true; } } else if (instruction->opcode() == HloOpcode::kRecvDone) { auto recv_done_instruction = DynCast<HloRecvDoneInstruction>(instruction); CHECK(recv_done_instruction); if (remove_comm_ || (remove_host_transfer_ && recv_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveRecvAndRecvDone(instruction, &removed).status()); changed = true; } } else if (remove_comm_ && IsCollective(instruction) && !instruction->parent()->IsFusionComputation() && (instruction->opcode() != HloOpcode::kAsyncStart && instruction->opcode() != HloOpcode::kAsyncUpdate)) { // We do not remove kAsyncStart or kAsyncUpdate here since we expect // them to be removed as a part of the async chain above. // We should remove the async chain all together because the async // wrapped computation is only associated with the AsyncStart. So we // need to refer to the AsyncStart in order to determine whether // the Done or the Update wraps a collective. if (instruction->opcode() == HloOpcode::kAsyncDone) { while (instruction->opcode() == HloOpcode::kAsyncDone || instruction->opcode() == HloOpcode::kAsyncUpdate || instruction->opcode() == HloOpcode::kAsyncStart) { HloInstruction* operand = instruction->mutable_operand(0); VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); instruction = operand; } } else { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); } changed = true; } else if (remove_comm_ && (instruction->opcode() == HloOpcode::kPartitionId || instruction->opcode() == HloOpcode::kReplicaId || (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == "SliceId"))) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveId(instruction)); changed = true; } } } HloDCE hlo_dce; TF_ASSIGN_OR_RETURN(bool dce_changed, hlo_dce.Run(module, execution_threads)); changed |= dce_changed; // Fix the schedule if the module was scheduled. if (changed && module->has_schedule()) { TF_RETURN_IF_ERROR(module->schedule().Update()); } XLA_VLOG_LINES(3, module->ToString()); return changed; } VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); XLA_VLOG_LINES(3, module->ToString());
#include "xla/tools/hlo_control_flow_flattening.h" #include <memory> #include <utility> #include "absl/strings/str_replace.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/collective_ops_utils.h" #include "xla/service/despecializer.h" #include "xla/service/hlo_verifier.h" #include "xla/service/spmd/spmd_partitioner.h" #include "xla/tests/hlo_test_base.h" #include "tsl/lib/core/status_test_util.h" class HloControlFlowFlatteningTest : public HloTestBase { public: absl::StatusOr<std::unique_ptr<HloModule>> PartitionComputation( std::unique_ptr<VerifiedHloModule> hlo_module, int64_t num_devices = 2) { spmd::SpmdPartitionerOptions options; auto collective_ops_creator = spmd::GetDefaultCollectiveOpsCreator(num_devices, /*num_replicas=*/1); collective_ops_creator.create_cross_partition_all_gather = nullptr; HloModuleConfig config = GetModuleConfigForTest(); config.set_use_spmd_partitioning(true); config.set_num_partitions(num_devices); HloPassPipeline pass("spmd-partitioning"); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); pass.AddPass<spmd::SpmdPartitioner>(num_devices, /*num_replicas=*/1, options, collective_ops_creator); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); TF_RETURN_IF_ERROR(pass.Run(hlo_module.get()).status()); return absl::StatusOr<std::unique_ptr<HloModule>>(std::move(hlo_module)); } }; TEST_F(HloControlFlowFlatteningTest, InfeedPreserveLayout) { absl::string_view hlo_string = R"( HloModule Infeed ENTRY Infeed { after-all = token[] after-all() ROOT infeed = ((bf16[3]{0}, s32[12,5]{0,1:T(8,128)}), token[]) infeed(after-all) } )"; TF_ASSERT_OK_AND_ASSIGN(auto module, ParseAndReturnVerifiedModule(hlo_string)); Shape root_shape = module->entry_computation()->root_instruction()->shape(); HloControlFlowFlattening flattening( HloControlFlowFlattening::Options{/*while_execution_count=*/3}); EXPECT_TRUE(flattening.Run(module.get()).value()); TF_ASSERT_OK(HloVerifier(/*layout_sensitive=*/true, /*allow_mixed_precision=*/true) .Run(module.get()) .status()); auto tuple = module->entry_computation()->root_instruction(); EXPECT_THAT(tuple, op::Tuple(op::CustomCall(), op::AfterAll())); EXPECT_EQ(tuple->shape(), root_shape); }
HloControlFlowFlatteningTest_MatchGtUseInferedLoopCount
xla/tools/hlo_control_flow_flattening_test.cc
HloInstruction* CreateConstant(const Shape& shape, HloComputation* computation) { if (shape.IsTuple()) { std::vector<HloInstruction*> tuple_arguments(shape.tuple_shapes_size()); for (int index = 0; index < shape.tuple_shapes_size(); ++index) { tuple_arguments[index] = CreateConstant(shape.tuple_shapes(index), computation); } return computation->AddInstruction( HloInstruction::CreateTuple(tuple_arguments)); } else { return computation->AddInstruction( HloInstruction::CreateConstant(Literal::CreateFromShape(shape))); } } void PrintSubexpression(HloInstruction* inst, int depth) { if (depth == 0) { return; } for (auto* operand : inst->operands()) { PrintSubexpression(operand, depth - 1); } VLOG(2) << inst->ToString(); } VLOG(2) << inst->ToString(); bool IsConstantScalarInt(const HloInstruction* inst) { return inst->opcode() == HloOpcode::kConstant && ShapeUtil::IsEffectiveScalar(inst->shape()) && inst->shape().IsInteger(); } bool IsNotContainedInLoop(const HloInstruction& while_hlo, const CallGraph& call_graph) { const HloComputation* computation = while_hlo.parent(); while (!computation->IsEntryComputation()) { auto& node = call_graph.GetNode(computation); CHECK_EQ(node.caller_callsites().size(), 1) << "The module is not flattened!"; auto& callsite = node.caller_callsites()[0]; if (callsite.instruction()->opcode() == HloOpcode::kWhile) { // Another while loop has been found traversing up the call tree. return false; } computation = callsite.instruction()->parent(); } // No calling while loops were found. return true; } int GetLoopBound(const HloInstruction& while_hlo, const int default_loop_count, const int max_loop_count) { HloInstruction* condition = while_hlo.while_condition()->root_instruction(); if (condition->opcode() == HloOpcode::kCompare) { int64_t value = 0; Comparison::Direction cmp = condition->comparison_direction(); if ((cmp == Comparison::Direction::kLt || cmp == Comparison::Direction::kLe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(1))) { value = *condition->operand(1)->literal().GetFirstInteger(); } else if ((cmp == Comparison::Direction::kGt || cmp == Comparison::Direction::kGe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(0))) { value = *condition->operand(0)->literal().GetFirstInteger(); } if (value > 0) { // Caps to a max loop count to avoid long execution times. return std::min(value, static_cast<int64_t>(max_loop_count)); } } return default_loop_count; } int GetLoopBoundWithOuterLoopMax(const HloInstruction& while_hlo, const CallGraph& call_graph, const int default_loop_count, const int max_outer_loop_count, const int max_loop_count) { int loop_bound = GetLoopBound(while_hlo, default_loop_count, max_loop_count); if (loop_bound > max_outer_loop_count) { // First does the inexpensive loop bound check to avoid as many // expensive graph traversals in IsNotContainedInLoop as possible. if (IsNotContainedInLoop(while_hlo, call_graph)) { return max_outer_loop_count; } } return loop_bound; } absl::Status HloControlFlowFlattening::FlattenWhileLoop( HloInstruction* while_hlo, const CallGraph& call_graph) const { CHECK_EQ(while_hlo->opcode(), HloOpcode::kWhile); HloComputation* computation = while_hlo->parent(); // Add a new induction variable. HloInstruction* initialization = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(0))); // Create a new while operand with the induction variable added. HloInstruction* old_tuple = while_hlo->mutable_operand(0); HloInstruction* new_tuple = TupleUtil::AppendSuffix(old_tuple, {initialization}); int new_tuple_size = new_tuple->shape().tuple_shapes().size(); TF_RETURN_IF_ERROR(while_hlo->ReplaceOperandWithDifferentShape(0, new_tuple)); auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; // Replace the given tuple-shaped instruction of size N in each of its // non-get-tuple-element users with a new tuple instruction which has the // first N - 1 elements. auto replace_non_gte_users = [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; { // Add the new variable to the while loop condition. HloComputation* condition = while_hlo->while_condition(); TF_RETURN_IF_ERROR(change_op_shape(condition->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(condition->parameter_instruction(0)).status()); if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); PrintSubexpression(condition->root_instruction(), /*depth=*/3); } const int loop_bound = GetLoopBoundWithOuterLoopMax( *while_hlo, call_graph, while_execution_count_, max_outer_loop_count_, max_loop_count_); VLOG(1) << "loop_bound = " << loop_bound; HloInstruction* limit = condition->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(loop_bound))); Shape shape = initialization->shape(); HloInstruction* induction_variable = condition->AddInstruction(HloInstruction::CreateGetTupleElement( shape, condition->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* compare = condition->AddInstruction(HloInstruction::CreateCompare( ShapeUtil::MakeShape(PRED, {}), induction_variable, limit, ComparisonDirection::kLt)); TF_RETURN_IF_ERROR( condition->ReplaceInstruction(condition->root_instruction(), compare)); } { // Add the new variable to the while loop body. HloComputation* body = while_hlo->while_body(); TF_RETURN_IF_ERROR(change_op_shape(body->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(body->parameter_instruction(0)).status()); HloInstruction* old_root = body->root_instruction(); Shape shape = initialization->shape(); HloInstruction* induction_variable = body->AddInstruction(HloInstruction::CreateGetTupleElement( shape, body->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* increment = body->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(1))); induction_variable = body->AddInstruction(HloInstruction::CreateBinary( shape, HloOpcode::kAdd, induction_variable, increment)); HloInstruction* new_root = TupleUtil::AppendSuffix(old_root, {induction_variable}); body->set_root_instruction(new_root, /*accept_different_shape=*/true); } // Snapshot the users of while hlo before we add new users. std::vector<HloInstruction*> while_users(while_hlo->users().begin(), while_hlo->users().end()); // Take care of the users of this while loop. TF_RETURN_IF_ERROR(change_op_shape(while_hlo)); TF_ASSIGN_OR_RETURN(HloInstruction * prefix, replace_non_gte_users(while_hlo)); // If the while loop had been the root of its computation, make the prefix new // root. if (while_hlo->parent()->root_instruction() == while_hlo) { // We need to set accept_different_shape=true to reset the root shape to the // original, because we have already changed the shape of the old root // (while). if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix(while_hlo, new_tuple_size - 1); } while_hlo->parent()->set_root_instruction(prefix, /*accept_different_shape=*/true); } return absl::OkStatus(); } auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); VLOG(1) << "loop_bound = " << loop_bound; absl::Status HloControlFlowFlattening::RemoveInfeed( HloInstruction* infeed_hlo) const { CHECK_EQ(infeed_hlo->opcode(), HloOpcode::kInfeed); HloComputation* computation = infeed_hlo->parent(); CHECK_EQ(infeed_hlo->shape().tuple_shapes_size(), 2); const Shape& infeed_shape = ShapeUtil::GetSubshape(infeed_hlo->shape(), {0}); HloInstruction* custom_call = computation->AddInstruction( HloInstruction::CreateCustomCall(infeed_shape, {}, kNopCustomCallTarget)); // Create a new tuple consisting of the constant and the token that was // originally the operand of infeed, and replace the infeed operation. auto new_tuple = HloInstruction::CreateTuple( {custom_call, infeed_hlo->mutable_operand(0)}); TF_RETURN_IF_ERROR( computation->ReplaceWithNewInstruction(infeed_hlo, std::move(new_tuple))); custom_call->SetAndSanitizeName(infeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveRecvAndRecvDone( HloInstruction* recv_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(recv_done->opcode(), HloOpcode::kRecvDone); CHECK_EQ(recv_done->operand_count(), 1); HloInstruction* recv = recv_done->mutable_operand(0); CHECK_EQ(recv->opcode(), HloOpcode::kRecv); HloComputation* computation = recv_done->parent(); CHECK_EQ(recv_done->shape().tuple_shapes_size(), 2); HloModule* module = computation->parent(); HloInstruction* custom_call_recv = computation->AddInstruction(HloInstruction::CreateCustomCall( recv->shape(), recv->operands(), kNopCustomCallTarget)); std::string original_recv_name(recv->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv, custom_call_recv); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(recv, custom_call_recv)); custom_call_recv->SetAndSanitizeName(original_recv_name); std::string original_recv_done_name(recv_done->name()); HloInstruction* custom_call_recv_done = computation->AddInstruction( HloInstruction::CreateCustomCall( recv_done->shape(), recv_done->operands(), kNopCustomCallTarget), recv_done->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv_done, custom_call_recv_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(recv_done, custom_call_recv_done)); custom_call_recv_done->SetAndSanitizeName(original_recv_done_name); return std::make_pair(custom_call_recv, custom_call_recv_done); } absl::Status HloControlFlowFlattening::RemoveOutfeed( HloInstruction* outfeed_hlo) const { CHECK_EQ(outfeed_hlo->opcode(), HloOpcode::kOutfeed); HloComputation* computation = outfeed_hlo->parent(); // Replace the outfeed with a no-op custom call with side effect to ensure the // operands aren't DCE'd. HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( outfeed_hlo->shape(), outfeed_hlo->operands(), kNopReturnTokenCustomCallTarget)); Cast<HloCustomCallInstruction>(custom_call) ->set_custom_call_has_side_effect(true); // For SPMD graphs, partitioner requires that side-effecting custom calls have // a sharding that is non-replicated. custom_call->set_sharding(HloSharding::Manual()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(outfeed_hlo, custom_call)); custom_call->SetAndSanitizeName(outfeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveSendAndSendDone( HloInstruction* send_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(send_done->opcode(), HloOpcode::kSendDone); CHECK_EQ(send_done->operand_count(), 1); HloInstruction* send = send_done->mutable_operand(0); CHECK_EQ(send->opcode(), HloOpcode::kSend); HloComputation* computation = send_done->parent(); HloModule* module = computation->parent(); HloInstruction* custom_call_send = computation->AddInstruction(HloInstruction::CreateCustomCall( send->shape(), send->operands(), kNopCustomCallTarget)); std::string original_send_name(send->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send, custom_call_send); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(send, custom_call_send)); custom_call_send->SetAndSanitizeName(original_send_name); HloInstruction* custom_call_send_done = computation->AddInstruction(HloInstruction::CreateCustomCall( send_done->shape(), send_done->operands(), kNopReturnTokenCustomCallTarget)); std::string original_send_done_name(send_done->name()); Cast<HloCustomCallInstruction>(custom_call_send_done) ->set_custom_call_has_side_effect(true); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send_done, custom_call_send_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(send_done, custom_call_send_done)); custom_call_send_done->SetAndSanitizeName(original_send_done_name); return std::make_pair(custom_call_send, custom_call_send_done); } absl::StatusOr<HloInstruction*> HloControlFlowFlattening::RemoveCollective( HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( hlo->shape(), hlo->operands(), kNopCustomCallTarget)); // Copy backend config. This is necessary for a collective op in megacore // fusion. custom_call->CopyBackendConfigFrom(hlo); HloModule* module = computation->parent(); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, hlo, custom_call); } std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, custom_call)); custom_call->SetAndSanitizeName(original_op_name); return custom_call; } absl::Status HloControlFlowFlattening::RemoveId(HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* zero = CreateConstant(hlo->shape(), computation); std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, zero)); zero->SetAndSanitizeName(original_op_name); return absl::OkStatus(); } absl::StatusOr<bool> HloControlFlowFlattening::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { auto call_graph = CallGraph::Build(module); bool changed = false; absl::flat_hash_set<HloInstruction*> removed; for (HloComputation* computation : module->computations(execution_threads)) { // Do not change computations that are wrapped by async calls. Instead we // remove the async callers if needed. if (computation->IsAsyncComputation()) { continue; } for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (removed.contains(instruction)) { // Skip the instruction if it is already removed. continue; } if (flatten_while_loop_ && instruction->opcode() == HloOpcode::kWhile) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(FlattenWhileLoop(instruction, *call_graph)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kInfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveInfeed(instruction)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kOutfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveOutfeed(instruction)); changed = true; } else if (instruction->opcode() == HloOpcode::kSendDone) { auto send_done_instruction = DynCast<HloSendDoneInstruction>(instruction); CHECK(send_done_instruction); if (remove_comm_ || (remove_host_transfer_ && send_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveSendAndSendDone(instruction, &removed).status()); changed = true; } } else if (instruction->opcode() == HloOpcode::kRecvDone) { auto recv_done_instruction = DynCast<HloRecvDoneInstruction>(instruction); CHECK(recv_done_instruction); if (remove_comm_ || (remove_host_transfer_ && recv_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveRecvAndRecvDone(instruction, &removed).status()); changed = true; } } else if (remove_comm_ && IsCollective(instruction) && !instruction->parent()->IsFusionComputation() && (instruction->opcode() != HloOpcode::kAsyncStart && instruction->opcode() != HloOpcode::kAsyncUpdate)) { // We do not remove kAsyncStart or kAsyncUpdate here since we expect // them to be removed as a part of the async chain above. // We should remove the async chain all together because the async // wrapped computation is only associated with the AsyncStart. So we // need to refer to the AsyncStart in order to determine whether // the Done or the Update wraps a collective. if (instruction->opcode() == HloOpcode::kAsyncDone) { while (instruction->opcode() == HloOpcode::kAsyncDone || instruction->opcode() == HloOpcode::kAsyncUpdate || instruction->opcode() == HloOpcode::kAsyncStart) { HloInstruction* operand = instruction->mutable_operand(0); VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); instruction = operand; } } else { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); } changed = true; } else if (remove_comm_ && (instruction->opcode() == HloOpcode::kPartitionId || instruction->opcode() == HloOpcode::kReplicaId || (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == "SliceId"))) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveId(instruction)); changed = true; } } } HloDCE hlo_dce; TF_ASSIGN_OR_RETURN(bool dce_changed, hlo_dce.Run(module, execution_threads)); changed |= dce_changed; // Fix the schedule if the module was scheduled. if (changed && module->has_schedule()) { TF_RETURN_IF_ERROR(module->schedule().Update()); } XLA_VLOG_LINES(3, module->ToString()); return changed; } VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); XLA_VLOG_LINES(3, module->ToString());
#include "xla/tools/hlo_control_flow_flattening.h" #include <memory> #include <utility> #include "absl/strings/str_replace.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/collective_ops_utils.h" #include "xla/service/despecializer.h" #include "xla/service/hlo_verifier.h" #include "xla/service/spmd/spmd_partitioner.h" #include "xla/tests/hlo_test_base.h" #include "tsl/lib/core/status_test_util.h" class HloControlFlowFlatteningTest : public HloTestBase { public: absl::StatusOr<std::unique_ptr<HloModule>> PartitionComputation( std::unique_ptr<VerifiedHloModule> hlo_module, int64_t num_devices = 2) { spmd::SpmdPartitionerOptions options; auto collective_ops_creator = spmd::GetDefaultCollectiveOpsCreator(num_devices, /*num_replicas=*/1); collective_ops_creator.create_cross_partition_all_gather = nullptr; HloModuleConfig config = GetModuleConfigForTest(); config.set_use_spmd_partitioning(true); config.set_num_partitions(num_devices); HloPassPipeline pass("spmd-partitioning"); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); pass.AddPass<spmd::SpmdPartitioner>(num_devices, /*num_replicas=*/1, options, collective_ops_creator); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); TF_RETURN_IF_ERROR(pass.Run(hlo_module.get()).status()); return absl::StatusOr<std::unique_ptr<HloModule>>(std::move(hlo_module)); } }; TEST_F(HloControlFlowFlatteningTest, MatchGtUseInferedLoopCount) { absl::string_view hlo_string = R"( HloModule While While.body { loop_var.1 = (s32[], s32[3]{0}) parameter(0) get-tuple-element.1 = s32[] get-tuple-element(loop_var.1), index=0 constant.1 = s32[] constant(1) add = s32[] add(get-tuple-element.1, constant.1) get-tuple-element.2 = s32[3]{0} get-tuple-element(loop_var.1), index=1 multiply = s32[3]{0} multiply(get-tuple-element.2, get-tuple-element.2) ROOT tuple = (s32[], s32[3]{0}) tuple(add, multiply) } While.condition { loop_var.2 = (s32[], s32[3]{0}) parameter(0) get-tuple-element.3 = s32[] get-tuple-element(loop_var.2), index=0 constant.2 = s32[] constant(50) ROOT greater-than = pred[] compare(constant.2, get-tuple-element.3), direction=GT } ENTRY While { constant.3 = s32[] constant(42) constant.4 = s32[3]{0} constant({0, 1, 2}) tuple.1 = (s32[], s32[3]{0}) tuple(constant.3, constant.4) ROOT while = (s32[], s32[3]{0}) while(tuple.1), condition=While.condition, body=While.body } )"; TF_ASSERT_OK_AND_ASSIGN(auto module, ParseAndReturnVerifiedModule(hlo_string)); EXPECT_EQ(GetLoopBound(*module->entry_computation()->root_instruction(), 123, kDefaultMaxLoopCount), 50); }
HloControlFlowFlatteningTest_MatchLtUseInferedLoopCount
xla/tools/hlo_control_flow_flattening_test.cc
HloInstruction* CreateConstant(const Shape& shape, HloComputation* computation) { if (shape.IsTuple()) { std::vector<HloInstruction*> tuple_arguments(shape.tuple_shapes_size()); for (int index = 0; index < shape.tuple_shapes_size(); ++index) { tuple_arguments[index] = CreateConstant(shape.tuple_shapes(index), computation); } return computation->AddInstruction( HloInstruction::CreateTuple(tuple_arguments)); } else { return computation->AddInstruction( HloInstruction::CreateConstant(Literal::CreateFromShape(shape))); } } void PrintSubexpression(HloInstruction* inst, int depth) { if (depth == 0) { return; } for (auto* operand : inst->operands()) { PrintSubexpression(operand, depth - 1); } VLOG(2) << inst->ToString(); } VLOG(2) << inst->ToString(); bool IsConstantScalarInt(const HloInstruction* inst) { return inst->opcode() == HloOpcode::kConstant && ShapeUtil::IsEffectiveScalar(inst->shape()) && inst->shape().IsInteger(); } bool IsNotContainedInLoop(const HloInstruction& while_hlo, const CallGraph& call_graph) { const HloComputation* computation = while_hlo.parent(); while (!computation->IsEntryComputation()) { auto& node = call_graph.GetNode(computation); CHECK_EQ(node.caller_callsites().size(), 1) << "The module is not flattened!"; auto& callsite = node.caller_callsites()[0]; if (callsite.instruction()->opcode() == HloOpcode::kWhile) { // Another while loop has been found traversing up the call tree. return false; } computation = callsite.instruction()->parent(); } // No calling while loops were found. return true; } int GetLoopBound(const HloInstruction& while_hlo, const int default_loop_count, const int max_loop_count) { HloInstruction* condition = while_hlo.while_condition()->root_instruction(); if (condition->opcode() == HloOpcode::kCompare) { int64_t value = 0; Comparison::Direction cmp = condition->comparison_direction(); if ((cmp == Comparison::Direction::kLt || cmp == Comparison::Direction::kLe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(1))) { value = *condition->operand(1)->literal().GetFirstInteger(); } else if ((cmp == Comparison::Direction::kGt || cmp == Comparison::Direction::kGe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(0))) { value = *condition->operand(0)->literal().GetFirstInteger(); } if (value > 0) { // Caps to a max loop count to avoid long execution times. return std::min(value, static_cast<int64_t>(max_loop_count)); } } return default_loop_count; } int GetLoopBoundWithOuterLoopMax(const HloInstruction& while_hlo, const CallGraph& call_graph, const int default_loop_count, const int max_outer_loop_count, const int max_loop_count) { int loop_bound = GetLoopBound(while_hlo, default_loop_count, max_loop_count); if (loop_bound > max_outer_loop_count) { // First does the inexpensive loop bound check to avoid as many // expensive graph traversals in IsNotContainedInLoop as possible. if (IsNotContainedInLoop(while_hlo, call_graph)) { return max_outer_loop_count; } } return loop_bound; } absl::Status HloControlFlowFlattening::FlattenWhileLoop( HloInstruction* while_hlo, const CallGraph& call_graph) const { CHECK_EQ(while_hlo->opcode(), HloOpcode::kWhile); HloComputation* computation = while_hlo->parent(); // Add a new induction variable. HloInstruction* initialization = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(0))); // Create a new while operand with the induction variable added. HloInstruction* old_tuple = while_hlo->mutable_operand(0); HloInstruction* new_tuple = TupleUtil::AppendSuffix(old_tuple, {initialization}); int new_tuple_size = new_tuple->shape().tuple_shapes().size(); TF_RETURN_IF_ERROR(while_hlo->ReplaceOperandWithDifferentShape(0, new_tuple)); auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; // Replace the given tuple-shaped instruction of size N in each of its // non-get-tuple-element users with a new tuple instruction which has the // first N - 1 elements. auto replace_non_gte_users = [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; { // Add the new variable to the while loop condition. HloComputation* condition = while_hlo->while_condition(); TF_RETURN_IF_ERROR(change_op_shape(condition->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(condition->parameter_instruction(0)).status()); if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); PrintSubexpression(condition->root_instruction(), /*depth=*/3); } const int loop_bound = GetLoopBoundWithOuterLoopMax( *while_hlo, call_graph, while_execution_count_, max_outer_loop_count_, max_loop_count_); VLOG(1) << "loop_bound = " << loop_bound; HloInstruction* limit = condition->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(loop_bound))); Shape shape = initialization->shape(); HloInstruction* induction_variable = condition->AddInstruction(HloInstruction::CreateGetTupleElement( shape, condition->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* compare = condition->AddInstruction(HloInstruction::CreateCompare( ShapeUtil::MakeShape(PRED, {}), induction_variable, limit, ComparisonDirection::kLt)); TF_RETURN_IF_ERROR( condition->ReplaceInstruction(condition->root_instruction(), compare)); } { // Add the new variable to the while loop body. HloComputation* body = while_hlo->while_body(); TF_RETURN_IF_ERROR(change_op_shape(body->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(body->parameter_instruction(0)).status()); HloInstruction* old_root = body->root_instruction(); Shape shape = initialization->shape(); HloInstruction* induction_variable = body->AddInstruction(HloInstruction::CreateGetTupleElement( shape, body->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* increment = body->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(1))); induction_variable = body->AddInstruction(HloInstruction::CreateBinary( shape, HloOpcode::kAdd, induction_variable, increment)); HloInstruction* new_root = TupleUtil::AppendSuffix(old_root, {induction_variable}); body->set_root_instruction(new_root, /*accept_different_shape=*/true); } // Snapshot the users of while hlo before we add new users. std::vector<HloInstruction*> while_users(while_hlo->users().begin(), while_hlo->users().end()); // Take care of the users of this while loop. TF_RETURN_IF_ERROR(change_op_shape(while_hlo)); TF_ASSIGN_OR_RETURN(HloInstruction * prefix, replace_non_gte_users(while_hlo)); // If the while loop had been the root of its computation, make the prefix new // root. if (while_hlo->parent()->root_instruction() == while_hlo) { // We need to set accept_different_shape=true to reset the root shape to the // original, because we have already changed the shape of the old root // (while). if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix(while_hlo, new_tuple_size - 1); } while_hlo->parent()->set_root_instruction(prefix, /*accept_different_shape=*/true); } return absl::OkStatus(); } auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); VLOG(1) << "loop_bound = " << loop_bound; absl::Status HloControlFlowFlattening::RemoveInfeed( HloInstruction* infeed_hlo) const { CHECK_EQ(infeed_hlo->opcode(), HloOpcode::kInfeed); HloComputation* computation = infeed_hlo->parent(); CHECK_EQ(infeed_hlo->shape().tuple_shapes_size(), 2); const Shape& infeed_shape = ShapeUtil::GetSubshape(infeed_hlo->shape(), {0}); HloInstruction* custom_call = computation->AddInstruction( HloInstruction::CreateCustomCall(infeed_shape, {}, kNopCustomCallTarget)); // Create a new tuple consisting of the constant and the token that was // originally the operand of infeed, and replace the infeed operation. auto new_tuple = HloInstruction::CreateTuple( {custom_call, infeed_hlo->mutable_operand(0)}); TF_RETURN_IF_ERROR( computation->ReplaceWithNewInstruction(infeed_hlo, std::move(new_tuple))); custom_call->SetAndSanitizeName(infeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveRecvAndRecvDone( HloInstruction* recv_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(recv_done->opcode(), HloOpcode::kRecvDone); CHECK_EQ(recv_done->operand_count(), 1); HloInstruction* recv = recv_done->mutable_operand(0); CHECK_EQ(recv->opcode(), HloOpcode::kRecv); HloComputation* computation = recv_done->parent(); CHECK_EQ(recv_done->shape().tuple_shapes_size(), 2); HloModule* module = computation->parent(); HloInstruction* custom_call_recv = computation->AddInstruction(HloInstruction::CreateCustomCall( recv->shape(), recv->operands(), kNopCustomCallTarget)); std::string original_recv_name(recv->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv, custom_call_recv); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(recv, custom_call_recv)); custom_call_recv->SetAndSanitizeName(original_recv_name); std::string original_recv_done_name(recv_done->name()); HloInstruction* custom_call_recv_done = computation->AddInstruction( HloInstruction::CreateCustomCall( recv_done->shape(), recv_done->operands(), kNopCustomCallTarget), recv_done->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv_done, custom_call_recv_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(recv_done, custom_call_recv_done)); custom_call_recv_done->SetAndSanitizeName(original_recv_done_name); return std::make_pair(custom_call_recv, custom_call_recv_done); } absl::Status HloControlFlowFlattening::RemoveOutfeed( HloInstruction* outfeed_hlo) const { CHECK_EQ(outfeed_hlo->opcode(), HloOpcode::kOutfeed); HloComputation* computation = outfeed_hlo->parent(); // Replace the outfeed with a no-op custom call with side effect to ensure the // operands aren't DCE'd. HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( outfeed_hlo->shape(), outfeed_hlo->operands(), kNopReturnTokenCustomCallTarget)); Cast<HloCustomCallInstruction>(custom_call) ->set_custom_call_has_side_effect(true); // For SPMD graphs, partitioner requires that side-effecting custom calls have // a sharding that is non-replicated. custom_call->set_sharding(HloSharding::Manual()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(outfeed_hlo, custom_call)); custom_call->SetAndSanitizeName(outfeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveSendAndSendDone( HloInstruction* send_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(send_done->opcode(), HloOpcode::kSendDone); CHECK_EQ(send_done->operand_count(), 1); HloInstruction* send = send_done->mutable_operand(0); CHECK_EQ(send->opcode(), HloOpcode::kSend); HloComputation* computation = send_done->parent(); HloModule* module = computation->parent(); HloInstruction* custom_call_send = computation->AddInstruction(HloInstruction::CreateCustomCall( send->shape(), send->operands(), kNopCustomCallTarget)); std::string original_send_name(send->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send, custom_call_send); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(send, custom_call_send)); custom_call_send->SetAndSanitizeName(original_send_name); HloInstruction* custom_call_send_done = computation->AddInstruction(HloInstruction::CreateCustomCall( send_done->shape(), send_done->operands(), kNopReturnTokenCustomCallTarget)); std::string original_send_done_name(send_done->name()); Cast<HloCustomCallInstruction>(custom_call_send_done) ->set_custom_call_has_side_effect(true); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send_done, custom_call_send_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(send_done, custom_call_send_done)); custom_call_send_done->SetAndSanitizeName(original_send_done_name); return std::make_pair(custom_call_send, custom_call_send_done); } absl::StatusOr<HloInstruction*> HloControlFlowFlattening::RemoveCollective( HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( hlo->shape(), hlo->operands(), kNopCustomCallTarget)); // Copy backend config. This is necessary for a collective op in megacore // fusion. custom_call->CopyBackendConfigFrom(hlo); HloModule* module = computation->parent(); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, hlo, custom_call); } std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, custom_call)); custom_call->SetAndSanitizeName(original_op_name); return custom_call; } absl::Status HloControlFlowFlattening::RemoveId(HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* zero = CreateConstant(hlo->shape(), computation); std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, zero)); zero->SetAndSanitizeName(original_op_name); return absl::OkStatus(); } absl::StatusOr<bool> HloControlFlowFlattening::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { auto call_graph = CallGraph::Build(module); bool changed = false; absl::flat_hash_set<HloInstruction*> removed; for (HloComputation* computation : module->computations(execution_threads)) { // Do not change computations that are wrapped by async calls. Instead we // remove the async callers if needed. if (computation->IsAsyncComputation()) { continue; } for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (removed.contains(instruction)) { // Skip the instruction if it is already removed. continue; } if (flatten_while_loop_ && instruction->opcode() == HloOpcode::kWhile) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(FlattenWhileLoop(instruction, *call_graph)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kInfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveInfeed(instruction)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kOutfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveOutfeed(instruction)); changed = true; } else if (instruction->opcode() == HloOpcode::kSendDone) { auto send_done_instruction = DynCast<HloSendDoneInstruction>(instruction); CHECK(send_done_instruction); if (remove_comm_ || (remove_host_transfer_ && send_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveSendAndSendDone(instruction, &removed).status()); changed = true; } } else if (instruction->opcode() == HloOpcode::kRecvDone) { auto recv_done_instruction = DynCast<HloRecvDoneInstruction>(instruction); CHECK(recv_done_instruction); if (remove_comm_ || (remove_host_transfer_ && recv_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveRecvAndRecvDone(instruction, &removed).status()); changed = true; } } else if (remove_comm_ && IsCollective(instruction) && !instruction->parent()->IsFusionComputation() && (instruction->opcode() != HloOpcode::kAsyncStart && instruction->opcode() != HloOpcode::kAsyncUpdate)) { // We do not remove kAsyncStart or kAsyncUpdate here since we expect // them to be removed as a part of the async chain above. // We should remove the async chain all together because the async // wrapped computation is only associated with the AsyncStart. So we // need to refer to the AsyncStart in order to determine whether // the Done or the Update wraps a collective. if (instruction->opcode() == HloOpcode::kAsyncDone) { while (instruction->opcode() == HloOpcode::kAsyncDone || instruction->opcode() == HloOpcode::kAsyncUpdate || instruction->opcode() == HloOpcode::kAsyncStart) { HloInstruction* operand = instruction->mutable_operand(0); VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); instruction = operand; } } else { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); } changed = true; } else if (remove_comm_ && (instruction->opcode() == HloOpcode::kPartitionId || instruction->opcode() == HloOpcode::kReplicaId || (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == "SliceId"))) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveId(instruction)); changed = true; } } } HloDCE hlo_dce; TF_ASSIGN_OR_RETURN(bool dce_changed, hlo_dce.Run(module, execution_threads)); changed |= dce_changed; // Fix the schedule if the module was scheduled. if (changed && module->has_schedule()) { TF_RETURN_IF_ERROR(module->schedule().Update()); } XLA_VLOG_LINES(3, module->ToString()); return changed; } VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); XLA_VLOG_LINES(3, module->ToString());
#include "xla/tools/hlo_control_flow_flattening.h" #include <memory> #include <utility> #include "absl/strings/str_replace.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/collective_ops_utils.h" #include "xla/service/despecializer.h" #include "xla/service/hlo_verifier.h" #include "xla/service/spmd/spmd_partitioner.h" #include "xla/tests/hlo_test_base.h" #include "tsl/lib/core/status_test_util.h" class HloControlFlowFlatteningTest : public HloTestBase { public: absl::StatusOr<std::unique_ptr<HloModule>> PartitionComputation( std::unique_ptr<VerifiedHloModule> hlo_module, int64_t num_devices = 2) { spmd::SpmdPartitionerOptions options; auto collective_ops_creator = spmd::GetDefaultCollectiveOpsCreator(num_devices, /*num_replicas=*/1); collective_ops_creator.create_cross_partition_all_gather = nullptr; HloModuleConfig config = GetModuleConfigForTest(); config.set_use_spmd_partitioning(true); config.set_num_partitions(num_devices); HloPassPipeline pass("spmd-partitioning"); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); pass.AddPass<spmd::SpmdPartitioner>(num_devices, /*num_replicas=*/1, options, collective_ops_creator); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); TF_RETURN_IF_ERROR(pass.Run(hlo_module.get()).status()); return absl::StatusOr<std::unique_ptr<HloModule>>(std::move(hlo_module)); } }; TEST_F(HloControlFlowFlatteningTest, MatchLtUseInferedLoopCount) { absl::string_view hlo_string = R"( HloModule While While.body { loop_var.1 = (s32[], s32[3]{0}) parameter(0) get-tuple-element.1 = s32[] get-tuple-element(loop_var.1), index=0 constant.1 = s32[] constant(1) add = s32[] add(get-tuple-element.1, constant.1) get-tuple-element.2 = s32[3]{0} get-tuple-element(loop_var.1), index=1 multiply = s32[3]{0} multiply(get-tuple-element.2, get-tuple-element.2) ROOT tuple = (s32[], s32[3]{0}) tuple(add, multiply) } While.condition { loop_var.2 = (s32[], s32[3]{0}) parameter(0) get-tuple-element.3 = s32[] get-tuple-element(loop_var.2), index=0 constant.2 = s32[] constant(100) ROOT less-than = pred[] compare(get-tuple-element.3, constant.2), direction=LT } ENTRY While { constant.3 = s32[] constant(42) constant.4 = s32[3]{0} constant({0, 1, 2}) tuple.1 = (s32[], s32[3]{0}) tuple(constant.3, constant.4) ROOT while = (s32[], s32[3]{0}) while(tuple.1), condition=While.condition, body=While.body } )"; TF_ASSERT_OK_AND_ASSIGN(auto module, ParseAndReturnVerifiedModule(hlo_string)); EXPECT_EQ(GetLoopBound(*module->entry_computation()->root_instruction(), 123, kDefaultMaxLoopCount), 100); }
HloControlFlowFlatteningTest_MaxOuterLoopCount
xla/tools/hlo_control_flow_flattening_test.cc
HloInstruction* CreateConstant(const Shape& shape, HloComputation* computation) { if (shape.IsTuple()) { std::vector<HloInstruction*> tuple_arguments(shape.tuple_shapes_size()); for (int index = 0; index < shape.tuple_shapes_size(); ++index) { tuple_arguments[index] = CreateConstant(shape.tuple_shapes(index), computation); } return computation->AddInstruction( HloInstruction::CreateTuple(tuple_arguments)); } else { return computation->AddInstruction( HloInstruction::CreateConstant(Literal::CreateFromShape(shape))); } } void PrintSubexpression(HloInstruction* inst, int depth) { if (depth == 0) { return; } for (auto* operand : inst->operands()) { PrintSubexpression(operand, depth - 1); } VLOG(2) << inst->ToString(); } VLOG(2) << inst->ToString(); bool IsConstantScalarInt(const HloInstruction* inst) { return inst->opcode() == HloOpcode::kConstant && ShapeUtil::IsEffectiveScalar(inst->shape()) && inst->shape().IsInteger(); } bool IsNotContainedInLoop(const HloInstruction& while_hlo, const CallGraph& call_graph) { const HloComputation* computation = while_hlo.parent(); while (!computation->IsEntryComputation()) { auto& node = call_graph.GetNode(computation); CHECK_EQ(node.caller_callsites().size(), 1) << "The module is not flattened!"; auto& callsite = node.caller_callsites()[0]; if (callsite.instruction()->opcode() == HloOpcode::kWhile) { // Another while loop has been found traversing up the call tree. return false; } computation = callsite.instruction()->parent(); } // No calling while loops were found. return true; } int GetLoopBound(const HloInstruction& while_hlo, const int default_loop_count, const int max_loop_count) { HloInstruction* condition = while_hlo.while_condition()->root_instruction(); if (condition->opcode() == HloOpcode::kCompare) { int64_t value = 0; Comparison::Direction cmp = condition->comparison_direction(); if ((cmp == Comparison::Direction::kLt || cmp == Comparison::Direction::kLe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(1))) { value = *condition->operand(1)->literal().GetFirstInteger(); } else if ((cmp == Comparison::Direction::kGt || cmp == Comparison::Direction::kGe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(0))) { value = *condition->operand(0)->literal().GetFirstInteger(); } if (value > 0) { // Caps to a max loop count to avoid long execution times. return std::min(value, static_cast<int64_t>(max_loop_count)); } } return default_loop_count; } int GetLoopBoundWithOuterLoopMax(const HloInstruction& while_hlo, const CallGraph& call_graph, const int default_loop_count, const int max_outer_loop_count, const int max_loop_count) { int loop_bound = GetLoopBound(while_hlo, default_loop_count, max_loop_count); if (loop_bound > max_outer_loop_count) { // First does the inexpensive loop bound check to avoid as many // expensive graph traversals in IsNotContainedInLoop as possible. if (IsNotContainedInLoop(while_hlo, call_graph)) { return max_outer_loop_count; } } return loop_bound; } absl::Status HloControlFlowFlattening::FlattenWhileLoop( HloInstruction* while_hlo, const CallGraph& call_graph) const { CHECK_EQ(while_hlo->opcode(), HloOpcode::kWhile); HloComputation* computation = while_hlo->parent(); // Add a new induction variable. HloInstruction* initialization = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(0))); // Create a new while operand with the induction variable added. HloInstruction* old_tuple = while_hlo->mutable_operand(0); HloInstruction* new_tuple = TupleUtil::AppendSuffix(old_tuple, {initialization}); int new_tuple_size = new_tuple->shape().tuple_shapes().size(); TF_RETURN_IF_ERROR(while_hlo->ReplaceOperandWithDifferentShape(0, new_tuple)); auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; // Replace the given tuple-shaped instruction of size N in each of its // non-get-tuple-element users with a new tuple instruction which has the // first N - 1 elements. auto replace_non_gte_users = [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; { // Add the new variable to the while loop condition. HloComputation* condition = while_hlo->while_condition(); TF_RETURN_IF_ERROR(change_op_shape(condition->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(condition->parameter_instruction(0)).status()); if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); PrintSubexpression(condition->root_instruction(), /*depth=*/3); } const int loop_bound = GetLoopBoundWithOuterLoopMax( *while_hlo, call_graph, while_execution_count_, max_outer_loop_count_, max_loop_count_); VLOG(1) << "loop_bound = " << loop_bound; HloInstruction* limit = condition->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(loop_bound))); Shape shape = initialization->shape(); HloInstruction* induction_variable = condition->AddInstruction(HloInstruction::CreateGetTupleElement( shape, condition->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* compare = condition->AddInstruction(HloInstruction::CreateCompare( ShapeUtil::MakeShape(PRED, {}), induction_variable, limit, ComparisonDirection::kLt)); TF_RETURN_IF_ERROR( condition->ReplaceInstruction(condition->root_instruction(), compare)); } { // Add the new variable to the while loop body. HloComputation* body = while_hlo->while_body(); TF_RETURN_IF_ERROR(change_op_shape(body->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(body->parameter_instruction(0)).status()); HloInstruction* old_root = body->root_instruction(); Shape shape = initialization->shape(); HloInstruction* induction_variable = body->AddInstruction(HloInstruction::CreateGetTupleElement( shape, body->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* increment = body->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(1))); induction_variable = body->AddInstruction(HloInstruction::CreateBinary( shape, HloOpcode::kAdd, induction_variable, increment)); HloInstruction* new_root = TupleUtil::AppendSuffix(old_root, {induction_variable}); body->set_root_instruction(new_root, /*accept_different_shape=*/true); } // Snapshot the users of while hlo before we add new users. std::vector<HloInstruction*> while_users(while_hlo->users().begin(), while_hlo->users().end()); // Take care of the users of this while loop. TF_RETURN_IF_ERROR(change_op_shape(while_hlo)); TF_ASSIGN_OR_RETURN(HloInstruction * prefix, replace_non_gte_users(while_hlo)); // If the while loop had been the root of its computation, make the prefix new // root. if (while_hlo->parent()->root_instruction() == while_hlo) { // We need to set accept_different_shape=true to reset the root shape to the // original, because we have already changed the shape of the old root // (while). if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix(while_hlo, new_tuple_size - 1); } while_hlo->parent()->set_root_instruction(prefix, /*accept_different_shape=*/true); } return absl::OkStatus(); } auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); VLOG(1) << "loop_bound = " << loop_bound; absl::Status HloControlFlowFlattening::RemoveInfeed( HloInstruction* infeed_hlo) const { CHECK_EQ(infeed_hlo->opcode(), HloOpcode::kInfeed); HloComputation* computation = infeed_hlo->parent(); CHECK_EQ(infeed_hlo->shape().tuple_shapes_size(), 2); const Shape& infeed_shape = ShapeUtil::GetSubshape(infeed_hlo->shape(), {0}); HloInstruction* custom_call = computation->AddInstruction( HloInstruction::CreateCustomCall(infeed_shape, {}, kNopCustomCallTarget)); // Create a new tuple consisting of the constant and the token that was // originally the operand of infeed, and replace the infeed operation. auto new_tuple = HloInstruction::CreateTuple( {custom_call, infeed_hlo->mutable_operand(0)}); TF_RETURN_IF_ERROR( computation->ReplaceWithNewInstruction(infeed_hlo, std::move(new_tuple))); custom_call->SetAndSanitizeName(infeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveRecvAndRecvDone( HloInstruction* recv_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(recv_done->opcode(), HloOpcode::kRecvDone); CHECK_EQ(recv_done->operand_count(), 1); HloInstruction* recv = recv_done->mutable_operand(0); CHECK_EQ(recv->opcode(), HloOpcode::kRecv); HloComputation* computation = recv_done->parent(); CHECK_EQ(recv_done->shape().tuple_shapes_size(), 2); HloModule* module = computation->parent(); HloInstruction* custom_call_recv = computation->AddInstruction(HloInstruction::CreateCustomCall( recv->shape(), recv->operands(), kNopCustomCallTarget)); std::string original_recv_name(recv->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv, custom_call_recv); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(recv, custom_call_recv)); custom_call_recv->SetAndSanitizeName(original_recv_name); std::string original_recv_done_name(recv_done->name()); HloInstruction* custom_call_recv_done = computation->AddInstruction( HloInstruction::CreateCustomCall( recv_done->shape(), recv_done->operands(), kNopCustomCallTarget), recv_done->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv_done, custom_call_recv_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(recv_done, custom_call_recv_done)); custom_call_recv_done->SetAndSanitizeName(original_recv_done_name); return std::make_pair(custom_call_recv, custom_call_recv_done); } absl::Status HloControlFlowFlattening::RemoveOutfeed( HloInstruction* outfeed_hlo) const { CHECK_EQ(outfeed_hlo->opcode(), HloOpcode::kOutfeed); HloComputation* computation = outfeed_hlo->parent(); // Replace the outfeed with a no-op custom call with side effect to ensure the // operands aren't DCE'd. HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( outfeed_hlo->shape(), outfeed_hlo->operands(), kNopReturnTokenCustomCallTarget)); Cast<HloCustomCallInstruction>(custom_call) ->set_custom_call_has_side_effect(true); // For SPMD graphs, partitioner requires that side-effecting custom calls have // a sharding that is non-replicated. custom_call->set_sharding(HloSharding::Manual()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(outfeed_hlo, custom_call)); custom_call->SetAndSanitizeName(outfeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveSendAndSendDone( HloInstruction* send_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(send_done->opcode(), HloOpcode::kSendDone); CHECK_EQ(send_done->operand_count(), 1); HloInstruction* send = send_done->mutable_operand(0); CHECK_EQ(send->opcode(), HloOpcode::kSend); HloComputation* computation = send_done->parent(); HloModule* module = computation->parent(); HloInstruction* custom_call_send = computation->AddInstruction(HloInstruction::CreateCustomCall( send->shape(), send->operands(), kNopCustomCallTarget)); std::string original_send_name(send->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send, custom_call_send); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(send, custom_call_send)); custom_call_send->SetAndSanitizeName(original_send_name); HloInstruction* custom_call_send_done = computation->AddInstruction(HloInstruction::CreateCustomCall( send_done->shape(), send_done->operands(), kNopReturnTokenCustomCallTarget)); std::string original_send_done_name(send_done->name()); Cast<HloCustomCallInstruction>(custom_call_send_done) ->set_custom_call_has_side_effect(true); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send_done, custom_call_send_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(send_done, custom_call_send_done)); custom_call_send_done->SetAndSanitizeName(original_send_done_name); return std::make_pair(custom_call_send, custom_call_send_done); } absl::StatusOr<HloInstruction*> HloControlFlowFlattening::RemoveCollective( HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( hlo->shape(), hlo->operands(), kNopCustomCallTarget)); // Copy backend config. This is necessary for a collective op in megacore // fusion. custom_call->CopyBackendConfigFrom(hlo); HloModule* module = computation->parent(); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, hlo, custom_call); } std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, custom_call)); custom_call->SetAndSanitizeName(original_op_name); return custom_call; } absl::Status HloControlFlowFlattening::RemoveId(HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* zero = CreateConstant(hlo->shape(), computation); std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, zero)); zero->SetAndSanitizeName(original_op_name); return absl::OkStatus(); } absl::StatusOr<bool> HloControlFlowFlattening::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { auto call_graph = CallGraph::Build(module); bool changed = false; absl::flat_hash_set<HloInstruction*> removed; for (HloComputation* computation : module->computations(execution_threads)) { // Do not change computations that are wrapped by async calls. Instead we // remove the async callers if needed. if (computation->IsAsyncComputation()) { continue; } for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (removed.contains(instruction)) { // Skip the instruction if it is already removed. continue; } if (flatten_while_loop_ && instruction->opcode() == HloOpcode::kWhile) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(FlattenWhileLoop(instruction, *call_graph)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kInfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveInfeed(instruction)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kOutfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveOutfeed(instruction)); changed = true; } else if (instruction->opcode() == HloOpcode::kSendDone) { auto send_done_instruction = DynCast<HloSendDoneInstruction>(instruction); CHECK(send_done_instruction); if (remove_comm_ || (remove_host_transfer_ && send_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveSendAndSendDone(instruction, &removed).status()); changed = true; } } else if (instruction->opcode() == HloOpcode::kRecvDone) { auto recv_done_instruction = DynCast<HloRecvDoneInstruction>(instruction); CHECK(recv_done_instruction); if (remove_comm_ || (remove_host_transfer_ && recv_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveRecvAndRecvDone(instruction, &removed).status()); changed = true; } } else if (remove_comm_ && IsCollective(instruction) && !instruction->parent()->IsFusionComputation() && (instruction->opcode() != HloOpcode::kAsyncStart && instruction->opcode() != HloOpcode::kAsyncUpdate)) { // We do not remove kAsyncStart or kAsyncUpdate here since we expect // them to be removed as a part of the async chain above. // We should remove the async chain all together because the async // wrapped computation is only associated with the AsyncStart. So we // need to refer to the AsyncStart in order to determine whether // the Done or the Update wraps a collective. if (instruction->opcode() == HloOpcode::kAsyncDone) { while (instruction->opcode() == HloOpcode::kAsyncDone || instruction->opcode() == HloOpcode::kAsyncUpdate || instruction->opcode() == HloOpcode::kAsyncStart) { HloInstruction* operand = instruction->mutable_operand(0); VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); instruction = operand; } } else { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); } changed = true; } else if (remove_comm_ && (instruction->opcode() == HloOpcode::kPartitionId || instruction->opcode() == HloOpcode::kReplicaId || (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == "SliceId"))) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveId(instruction)); changed = true; } } } HloDCE hlo_dce; TF_ASSIGN_OR_RETURN(bool dce_changed, hlo_dce.Run(module, execution_threads)); changed |= dce_changed; // Fix the schedule if the module was scheduled. if (changed && module->has_schedule()) { TF_RETURN_IF_ERROR(module->schedule().Update()); } XLA_VLOG_LINES(3, module->ToString()); return changed; } VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); XLA_VLOG_LINES(3, module->ToString());
#include "xla/tools/hlo_control_flow_flattening.h" #include <memory> #include <utility> #include "absl/strings/str_replace.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/collective_ops_utils.h" #include "xla/service/despecializer.h" #include "xla/service/hlo_verifier.h" #include "xla/service/spmd/spmd_partitioner.h" #include "xla/tests/hlo_test_base.h" #include "tsl/lib/core/status_test_util.h" class HloControlFlowFlatteningTest : public HloTestBase { public: absl::StatusOr<std::unique_ptr<HloModule>> PartitionComputation( std::unique_ptr<VerifiedHloModule> hlo_module, int64_t num_devices = 2) { spmd::SpmdPartitionerOptions options; auto collective_ops_creator = spmd::GetDefaultCollectiveOpsCreator(num_devices, /*num_replicas=*/1); collective_ops_creator.create_cross_partition_all_gather = nullptr; HloModuleConfig config = GetModuleConfigForTest(); config.set_use_spmd_partitioning(true); config.set_num_partitions(num_devices); HloPassPipeline pass("spmd-partitioning"); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); pass.AddPass<spmd::SpmdPartitioner>(num_devices, /*num_replicas=*/1, options, collective_ops_creator); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); TF_RETURN_IF_ERROR(pass.Run(hlo_module.get()).status()); return absl::StatusOr<std::unique_ptr<HloModule>>(std::move(hlo_module)); } }; TEST_F(HloControlFlowFlatteningTest, MaxOuterLoopCount) { absl::string_view hlo_string = R"( HloModule NestedWhileComp InnerBody { constant.8 = pred[] constant(false) parameter.5 = (s32[], s32[]) parameter(0) get-tuple-element.6 = s32[] get-tuple-element(parameter.5), index=0 constant.9 = s32[] constant(1) add.10 = s32[] add(get-tuple-element.6, constant.9) get-tuple-element.7 = s32[] get-tuple-element(parameter.5), index=1 constant.11 = s32[] constant(1) add.12 = s32[] add(get-tuple-element.7, constant.11) ROOT tuple.13 = (s32[], s32[]) tuple(add.10, add.12) } InnerCond { parameter.15 = (s32[], s32[]) parameter(0) get-tuple-element.17 = s32[] get-tuple-element(parameter.15), index=1 constant.18 = pred[] constant(false) get-tuple-element.16 = s32[] get-tuple-element(parameter.15), index=0 inner_bound = s32[] constant(100) ROOT compare.20 = pred[] compare(get-tuple-element.16, inner_bound), direction=LT } OuterBody { constant.24 = pred[] constant(false) constant.25 = s32[] constant(0) parameter.22 = (s32[]) parameter(0) get-tuple-element.23 = s32[] get-tuple-element(parameter.22), index=0 tuple.26 = (s32[], s32[]) tuple(constant.25, get-tuple-element.23) inner_while = (s32[], s32[]) while(tuple.26), condition=InnerCond, body=InnerBody get-tuple-element.28 = s32[] get-tuple-element(inner_while), index=0 get-tuple-element.29 = s32[] get-tuple-element(inner_while), index=1 tuple.30 = (s32[], s32[]) tuple(get-tuple-element.28, get-tuple-element.29) get-tuple-element.31 = s32[] get-tuple-element(tuple.30), index=0 get-tuple-element.32 = s32[] get-tuple-element(tuple.30), index=1 ROOT tuple.33 = (s32[]) tuple(get-tuple-element.32) } OuterCond { constant.37 = pred[] constant(false) parameter.35 = (s32[]) parameter(0) get-tuple-element.36 = s32[] get-tuple-element(parameter.35), index=0 outer_bound = s32[] constant(1000) ROOT compare.39 = pred[] compare(get-tuple-element.36, outer_bound), direction=LT } ENTRY NestedWhileComp { constant.1 = pred[] constant(false) constant.2 = s32[] constant(0) tuple.3 = (s32[]) tuple(constant.2) outer_while = (s32[]) while(tuple.3), condition=OuterCond, body=OuterBody get-tuple-element.41 = s32[] get-tuple-element(outer_while), index=0 tuple.42 = (s32[]) tuple(get-tuple-element.41) get-tuple-element.43 = s32[] get-tuple-element(tuple.42), index=0 ROOT tuple.44 = (s32[]) tuple(get-tuple-element.43) } )"; TF_ASSERT_OK_AND_ASSIGN(auto module, ParseAndReturnVerifiedModule(hlo_string)); constexpr int kWhileExecutionCount = 5; constexpr int kExistingInnerLoopCount = 100; constexpr int kMaxLoopCount = 10; HloControlFlowFlattening flattening(HloControlFlowFlattening::Options{ /*while_execution_count=*/kWhileExecutionCount, /*max_outer_loop_count=*/kMaxLoopCount}); EXPECT_TRUE(flattening.Run(module.get()).value()); TF_ASSERT_OK(HloVerifier(/*layout_sensitive=*/true, /*allow_mixed_precision=*/true) .Run(module.get()) .status()); LOG(INFO) << module->ToString(); auto* outer_while = module->entry_computation()->GetInstructionWithName("outer_while"); ASSERT_NE(outer_while, nullptr); // Checks that the outer while loop has changed its loop bound. CheckWhileBound(outer_while, kMaxLoopCount); auto* while_body = outer_while->while_body(); ASSERT_NE(while_body, nullptr); auto* inner_while = while_body->GetInstructionWithName("inner_while"); ASSERT_NE(inner_while, nullptr); // Checks that the inner loop bound has not changed. CheckWhileBound(inner_while, kExistingInnerLoopCount); }
HloControlFlowFlatteningTest_NotMatchEqUseDefaultLoopCount
xla/tools/hlo_control_flow_flattening_test.cc
HloInstruction* CreateConstant(const Shape& shape, HloComputation* computation) { if (shape.IsTuple()) { std::vector<HloInstruction*> tuple_arguments(shape.tuple_shapes_size()); for (int index = 0; index < shape.tuple_shapes_size(); ++index) { tuple_arguments[index] = CreateConstant(shape.tuple_shapes(index), computation); } return computation->AddInstruction( HloInstruction::CreateTuple(tuple_arguments)); } else { return computation->AddInstruction( HloInstruction::CreateConstant(Literal::CreateFromShape(shape))); } } void PrintSubexpression(HloInstruction* inst, int depth) { if (depth == 0) { return; } for (auto* operand : inst->operands()) { PrintSubexpression(operand, depth - 1); } VLOG(2) << inst->ToString(); } VLOG(2) << inst->ToString(); bool IsConstantScalarInt(const HloInstruction* inst) { return inst->opcode() == HloOpcode::kConstant && ShapeUtil::IsEffectiveScalar(inst->shape()) && inst->shape().IsInteger(); } bool IsNotContainedInLoop(const HloInstruction& while_hlo, const CallGraph& call_graph) { const HloComputation* computation = while_hlo.parent(); while (!computation->IsEntryComputation()) { auto& node = call_graph.GetNode(computation); CHECK_EQ(node.caller_callsites().size(), 1) << "The module is not flattened!"; auto& callsite = node.caller_callsites()[0]; if (callsite.instruction()->opcode() == HloOpcode::kWhile) { // Another while loop has been found traversing up the call tree. return false; } computation = callsite.instruction()->parent(); } // No calling while loops were found. return true; } int GetLoopBound(const HloInstruction& while_hlo, const int default_loop_count, const int max_loop_count) { HloInstruction* condition = while_hlo.while_condition()->root_instruction(); if (condition->opcode() == HloOpcode::kCompare) { int64_t value = 0; Comparison::Direction cmp = condition->comparison_direction(); if ((cmp == Comparison::Direction::kLt || cmp == Comparison::Direction::kLe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(1))) { value = *condition->operand(1)->literal().GetFirstInteger(); } else if ((cmp == Comparison::Direction::kGt || cmp == Comparison::Direction::kGe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(0))) { value = *condition->operand(0)->literal().GetFirstInteger(); } if (value > 0) { // Caps to a max loop count to avoid long execution times. return std::min(value, static_cast<int64_t>(max_loop_count)); } } return default_loop_count; } int GetLoopBoundWithOuterLoopMax(const HloInstruction& while_hlo, const CallGraph& call_graph, const int default_loop_count, const int max_outer_loop_count, const int max_loop_count) { int loop_bound = GetLoopBound(while_hlo, default_loop_count, max_loop_count); if (loop_bound > max_outer_loop_count) { // First does the inexpensive loop bound check to avoid as many // expensive graph traversals in IsNotContainedInLoop as possible. if (IsNotContainedInLoop(while_hlo, call_graph)) { return max_outer_loop_count; } } return loop_bound; } absl::Status HloControlFlowFlattening::FlattenWhileLoop( HloInstruction* while_hlo, const CallGraph& call_graph) const { CHECK_EQ(while_hlo->opcode(), HloOpcode::kWhile); HloComputation* computation = while_hlo->parent(); // Add a new induction variable. HloInstruction* initialization = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(0))); // Create a new while operand with the induction variable added. HloInstruction* old_tuple = while_hlo->mutable_operand(0); HloInstruction* new_tuple = TupleUtil::AppendSuffix(old_tuple, {initialization}); int new_tuple_size = new_tuple->shape().tuple_shapes().size(); TF_RETURN_IF_ERROR(while_hlo->ReplaceOperandWithDifferentShape(0, new_tuple)); auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; // Replace the given tuple-shaped instruction of size N in each of its // non-get-tuple-element users with a new tuple instruction which has the // first N - 1 elements. auto replace_non_gte_users = [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; { // Add the new variable to the while loop condition. HloComputation* condition = while_hlo->while_condition(); TF_RETURN_IF_ERROR(change_op_shape(condition->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(condition->parameter_instruction(0)).status()); if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); PrintSubexpression(condition->root_instruction(), /*depth=*/3); } const int loop_bound = GetLoopBoundWithOuterLoopMax( *while_hlo, call_graph, while_execution_count_, max_outer_loop_count_, max_loop_count_); VLOG(1) << "loop_bound = " << loop_bound; HloInstruction* limit = condition->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(loop_bound))); Shape shape = initialization->shape(); HloInstruction* induction_variable = condition->AddInstruction(HloInstruction::CreateGetTupleElement( shape, condition->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* compare = condition->AddInstruction(HloInstruction::CreateCompare( ShapeUtil::MakeShape(PRED, {}), induction_variable, limit, ComparisonDirection::kLt)); TF_RETURN_IF_ERROR( condition->ReplaceInstruction(condition->root_instruction(), compare)); } { // Add the new variable to the while loop body. HloComputation* body = while_hlo->while_body(); TF_RETURN_IF_ERROR(change_op_shape(body->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(body->parameter_instruction(0)).status()); HloInstruction* old_root = body->root_instruction(); Shape shape = initialization->shape(); HloInstruction* induction_variable = body->AddInstruction(HloInstruction::CreateGetTupleElement( shape, body->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* increment = body->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(1))); induction_variable = body->AddInstruction(HloInstruction::CreateBinary( shape, HloOpcode::kAdd, induction_variable, increment)); HloInstruction* new_root = TupleUtil::AppendSuffix(old_root, {induction_variable}); body->set_root_instruction(new_root, /*accept_different_shape=*/true); } // Snapshot the users of while hlo before we add new users. std::vector<HloInstruction*> while_users(while_hlo->users().begin(), while_hlo->users().end()); // Take care of the users of this while loop. TF_RETURN_IF_ERROR(change_op_shape(while_hlo)); TF_ASSIGN_OR_RETURN(HloInstruction * prefix, replace_non_gte_users(while_hlo)); // If the while loop had been the root of its computation, make the prefix new // root. if (while_hlo->parent()->root_instruction() == while_hlo) { // We need to set accept_different_shape=true to reset the root shape to the // original, because we have already changed the shape of the old root // (while). if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix(while_hlo, new_tuple_size - 1); } while_hlo->parent()->set_root_instruction(prefix, /*accept_different_shape=*/true); } return absl::OkStatus(); } auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); VLOG(1) << "loop_bound = " << loop_bound; absl::Status HloControlFlowFlattening::RemoveInfeed( HloInstruction* infeed_hlo) const { CHECK_EQ(infeed_hlo->opcode(), HloOpcode::kInfeed); HloComputation* computation = infeed_hlo->parent(); CHECK_EQ(infeed_hlo->shape().tuple_shapes_size(), 2); const Shape& infeed_shape = ShapeUtil::GetSubshape(infeed_hlo->shape(), {0}); HloInstruction* custom_call = computation->AddInstruction( HloInstruction::CreateCustomCall(infeed_shape, {}, kNopCustomCallTarget)); // Create a new tuple consisting of the constant and the token that was // originally the operand of infeed, and replace the infeed operation. auto new_tuple = HloInstruction::CreateTuple( {custom_call, infeed_hlo->mutable_operand(0)}); TF_RETURN_IF_ERROR( computation->ReplaceWithNewInstruction(infeed_hlo, std::move(new_tuple))); custom_call->SetAndSanitizeName(infeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveRecvAndRecvDone( HloInstruction* recv_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(recv_done->opcode(), HloOpcode::kRecvDone); CHECK_EQ(recv_done->operand_count(), 1); HloInstruction* recv = recv_done->mutable_operand(0); CHECK_EQ(recv->opcode(), HloOpcode::kRecv); HloComputation* computation = recv_done->parent(); CHECK_EQ(recv_done->shape().tuple_shapes_size(), 2); HloModule* module = computation->parent(); HloInstruction* custom_call_recv = computation->AddInstruction(HloInstruction::CreateCustomCall( recv->shape(), recv->operands(), kNopCustomCallTarget)); std::string original_recv_name(recv->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv, custom_call_recv); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(recv, custom_call_recv)); custom_call_recv->SetAndSanitizeName(original_recv_name); std::string original_recv_done_name(recv_done->name()); HloInstruction* custom_call_recv_done = computation->AddInstruction( HloInstruction::CreateCustomCall( recv_done->shape(), recv_done->operands(), kNopCustomCallTarget), recv_done->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv_done, custom_call_recv_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(recv_done, custom_call_recv_done)); custom_call_recv_done->SetAndSanitizeName(original_recv_done_name); return std::make_pair(custom_call_recv, custom_call_recv_done); } absl::Status HloControlFlowFlattening::RemoveOutfeed( HloInstruction* outfeed_hlo) const { CHECK_EQ(outfeed_hlo->opcode(), HloOpcode::kOutfeed); HloComputation* computation = outfeed_hlo->parent(); // Replace the outfeed with a no-op custom call with side effect to ensure the // operands aren't DCE'd. HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( outfeed_hlo->shape(), outfeed_hlo->operands(), kNopReturnTokenCustomCallTarget)); Cast<HloCustomCallInstruction>(custom_call) ->set_custom_call_has_side_effect(true); // For SPMD graphs, partitioner requires that side-effecting custom calls have // a sharding that is non-replicated. custom_call->set_sharding(HloSharding::Manual()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(outfeed_hlo, custom_call)); custom_call->SetAndSanitizeName(outfeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveSendAndSendDone( HloInstruction* send_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(send_done->opcode(), HloOpcode::kSendDone); CHECK_EQ(send_done->operand_count(), 1); HloInstruction* send = send_done->mutable_operand(0); CHECK_EQ(send->opcode(), HloOpcode::kSend); HloComputation* computation = send_done->parent(); HloModule* module = computation->parent(); HloInstruction* custom_call_send = computation->AddInstruction(HloInstruction::CreateCustomCall( send->shape(), send->operands(), kNopCustomCallTarget)); std::string original_send_name(send->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send, custom_call_send); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(send, custom_call_send)); custom_call_send->SetAndSanitizeName(original_send_name); HloInstruction* custom_call_send_done = computation->AddInstruction(HloInstruction::CreateCustomCall( send_done->shape(), send_done->operands(), kNopReturnTokenCustomCallTarget)); std::string original_send_done_name(send_done->name()); Cast<HloCustomCallInstruction>(custom_call_send_done) ->set_custom_call_has_side_effect(true); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send_done, custom_call_send_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(send_done, custom_call_send_done)); custom_call_send_done->SetAndSanitizeName(original_send_done_name); return std::make_pair(custom_call_send, custom_call_send_done); } absl::StatusOr<HloInstruction*> HloControlFlowFlattening::RemoveCollective( HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( hlo->shape(), hlo->operands(), kNopCustomCallTarget)); // Copy backend config. This is necessary for a collective op in megacore // fusion. custom_call->CopyBackendConfigFrom(hlo); HloModule* module = computation->parent(); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, hlo, custom_call); } std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, custom_call)); custom_call->SetAndSanitizeName(original_op_name); return custom_call; } absl::Status HloControlFlowFlattening::RemoveId(HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* zero = CreateConstant(hlo->shape(), computation); std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, zero)); zero->SetAndSanitizeName(original_op_name); return absl::OkStatus(); } absl::StatusOr<bool> HloControlFlowFlattening::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { auto call_graph = CallGraph::Build(module); bool changed = false; absl::flat_hash_set<HloInstruction*> removed; for (HloComputation* computation : module->computations(execution_threads)) { // Do not change computations that are wrapped by async calls. Instead we // remove the async callers if needed. if (computation->IsAsyncComputation()) { continue; } for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (removed.contains(instruction)) { // Skip the instruction if it is already removed. continue; } if (flatten_while_loop_ && instruction->opcode() == HloOpcode::kWhile) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(FlattenWhileLoop(instruction, *call_graph)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kInfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveInfeed(instruction)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kOutfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveOutfeed(instruction)); changed = true; } else if (instruction->opcode() == HloOpcode::kSendDone) { auto send_done_instruction = DynCast<HloSendDoneInstruction>(instruction); CHECK(send_done_instruction); if (remove_comm_ || (remove_host_transfer_ && send_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveSendAndSendDone(instruction, &removed).status()); changed = true; } } else if (instruction->opcode() == HloOpcode::kRecvDone) { auto recv_done_instruction = DynCast<HloRecvDoneInstruction>(instruction); CHECK(recv_done_instruction); if (remove_comm_ || (remove_host_transfer_ && recv_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveRecvAndRecvDone(instruction, &removed).status()); changed = true; } } else if (remove_comm_ && IsCollective(instruction) && !instruction->parent()->IsFusionComputation() && (instruction->opcode() != HloOpcode::kAsyncStart && instruction->opcode() != HloOpcode::kAsyncUpdate)) { // We do not remove kAsyncStart or kAsyncUpdate here since we expect // them to be removed as a part of the async chain above. // We should remove the async chain all together because the async // wrapped computation is only associated with the AsyncStart. So we // need to refer to the AsyncStart in order to determine whether // the Done or the Update wraps a collective. if (instruction->opcode() == HloOpcode::kAsyncDone) { while (instruction->opcode() == HloOpcode::kAsyncDone || instruction->opcode() == HloOpcode::kAsyncUpdate || instruction->opcode() == HloOpcode::kAsyncStart) { HloInstruction* operand = instruction->mutable_operand(0); VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); instruction = operand; } } else { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); } changed = true; } else if (remove_comm_ && (instruction->opcode() == HloOpcode::kPartitionId || instruction->opcode() == HloOpcode::kReplicaId || (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == "SliceId"))) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveId(instruction)); changed = true; } } } HloDCE hlo_dce; TF_ASSIGN_OR_RETURN(bool dce_changed, hlo_dce.Run(module, execution_threads)); changed |= dce_changed; // Fix the schedule if the module was scheduled. if (changed && module->has_schedule()) { TF_RETURN_IF_ERROR(module->schedule().Update()); } XLA_VLOG_LINES(3, module->ToString()); return changed; } VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); XLA_VLOG_LINES(3, module->ToString());
#include "xla/tools/hlo_control_flow_flattening.h" #include <memory> #include <utility> #include "absl/strings/str_replace.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/collective_ops_utils.h" #include "xla/service/despecializer.h" #include "xla/service/hlo_verifier.h" #include "xla/service/spmd/spmd_partitioner.h" #include "xla/tests/hlo_test_base.h" #include "tsl/lib/core/status_test_util.h" class HloControlFlowFlatteningTest : public HloTestBase { public: absl::StatusOr<std::unique_ptr<HloModule>> PartitionComputation( std::unique_ptr<VerifiedHloModule> hlo_module, int64_t num_devices = 2) { spmd::SpmdPartitionerOptions options; auto collective_ops_creator = spmd::GetDefaultCollectiveOpsCreator(num_devices, /*num_replicas=*/1); collective_ops_creator.create_cross_partition_all_gather = nullptr; HloModuleConfig config = GetModuleConfigForTest(); config.set_use_spmd_partitioning(true); config.set_num_partitions(num_devices); HloPassPipeline pass("spmd-partitioning"); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); pass.AddPass<spmd::SpmdPartitioner>(num_devices, /*num_replicas=*/1, options, collective_ops_creator); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); TF_RETURN_IF_ERROR(pass.Run(hlo_module.get()).status()); return absl::StatusOr<std::unique_ptr<HloModule>>(std::move(hlo_module)); } }; TEST_F(HloControlFlowFlatteningTest, NotMatchEqUseDefaultLoopCount) { absl::string_view hlo_string = R"( HloModule While While.body { loop_var.1 = (s32[], s32[3]{0}) parameter(0) get-tuple-element.1 = s32[] get-tuple-element(loop_var.1), index=0 constant.1 = s32[] constant(1) add = s32[] add(get-tuple-element.1, constant.1) get-tuple-element.2 = s32[3]{0} get-tuple-element(loop_var.1), index=1 multiply = s32[3]{0} multiply(get-tuple-element.2, get-tuple-element.2) ROOT tuple = (s32[], s32[3]{0}) tuple(add, multiply) } While.condition { loop_var.2 = (s32[], s32[3]{0}) parameter(0) get-tuple-element.3 = s32[] get-tuple-element(loop_var.2), index=0 constant.2 = s32[] constant(100) ROOT equal = pred[] compare(get-tuple-element.3, constant.2), direction=EQ } ENTRY While { constant.3 = s32[] constant(42) constant.4 = s32[3]{0} constant({0, 1, 2}) tuple.1 = (s32[], s32[3]{0}) tuple(constant.3, constant.4) ROOT while = (s32[], s32[3]{0}) while(tuple.1), condition=While.condition, body=While.body } )"; TF_ASSERT_OK_AND_ASSIGN(auto module, ParseAndReturnVerifiedModule(hlo_string)); EXPECT_EQ(GetLoopBound(*module->entry_computation()->root_instruction(), 123, kDefaultMaxLoopCount), 123); }
HloControlFlowFlatteningTest_Outfeed
xla/tools/hlo_control_flow_flattening_test.cc
HloInstruction* CreateConstant(const Shape& shape, HloComputation* computation) { if (shape.IsTuple()) { std::vector<HloInstruction*> tuple_arguments(shape.tuple_shapes_size()); for (int index = 0; index < shape.tuple_shapes_size(); ++index) { tuple_arguments[index] = CreateConstant(shape.tuple_shapes(index), computation); } return computation->AddInstruction( HloInstruction::CreateTuple(tuple_arguments)); } else { return computation->AddInstruction( HloInstruction::CreateConstant(Literal::CreateFromShape(shape))); } } void PrintSubexpression(HloInstruction* inst, int depth) { if (depth == 0) { return; } for (auto* operand : inst->operands()) { PrintSubexpression(operand, depth - 1); } VLOG(2) << inst->ToString(); } VLOG(2) << inst->ToString(); bool IsConstantScalarInt(const HloInstruction* inst) { return inst->opcode() == HloOpcode::kConstant && ShapeUtil::IsEffectiveScalar(inst->shape()) && inst->shape().IsInteger(); } bool IsNotContainedInLoop(const HloInstruction& while_hlo, const CallGraph& call_graph) { const HloComputation* computation = while_hlo.parent(); while (!computation->IsEntryComputation()) { auto& node = call_graph.GetNode(computation); CHECK_EQ(node.caller_callsites().size(), 1) << "The module is not flattened!"; auto& callsite = node.caller_callsites()[0]; if (callsite.instruction()->opcode() == HloOpcode::kWhile) { // Another while loop has been found traversing up the call tree. return false; } computation = callsite.instruction()->parent(); } // No calling while loops were found. return true; } int GetLoopBound(const HloInstruction& while_hlo, const int default_loop_count, const int max_loop_count) { HloInstruction* condition = while_hlo.while_condition()->root_instruction(); if (condition->opcode() == HloOpcode::kCompare) { int64_t value = 0; Comparison::Direction cmp = condition->comparison_direction(); if ((cmp == Comparison::Direction::kLt || cmp == Comparison::Direction::kLe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(1))) { value = *condition->operand(1)->literal().GetFirstInteger(); } else if ((cmp == Comparison::Direction::kGt || cmp == Comparison::Direction::kGe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(0))) { value = *condition->operand(0)->literal().GetFirstInteger(); } if (value > 0) { // Caps to a max loop count to avoid long execution times. return std::min(value, static_cast<int64_t>(max_loop_count)); } } return default_loop_count; } int GetLoopBoundWithOuterLoopMax(const HloInstruction& while_hlo, const CallGraph& call_graph, const int default_loop_count, const int max_outer_loop_count, const int max_loop_count) { int loop_bound = GetLoopBound(while_hlo, default_loop_count, max_loop_count); if (loop_bound > max_outer_loop_count) { // First does the inexpensive loop bound check to avoid as many // expensive graph traversals in IsNotContainedInLoop as possible. if (IsNotContainedInLoop(while_hlo, call_graph)) { return max_outer_loop_count; } } return loop_bound; } absl::Status HloControlFlowFlattening::FlattenWhileLoop( HloInstruction* while_hlo, const CallGraph& call_graph) const { CHECK_EQ(while_hlo->opcode(), HloOpcode::kWhile); HloComputation* computation = while_hlo->parent(); // Add a new induction variable. HloInstruction* initialization = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(0))); // Create a new while operand with the induction variable added. HloInstruction* old_tuple = while_hlo->mutable_operand(0); HloInstruction* new_tuple = TupleUtil::AppendSuffix(old_tuple, {initialization}); int new_tuple_size = new_tuple->shape().tuple_shapes().size(); TF_RETURN_IF_ERROR(while_hlo->ReplaceOperandWithDifferentShape(0, new_tuple)); auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; // Replace the given tuple-shaped instruction of size N in each of its // non-get-tuple-element users with a new tuple instruction which has the // first N - 1 elements. auto replace_non_gte_users = [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; { // Add the new variable to the while loop condition. HloComputation* condition = while_hlo->while_condition(); TF_RETURN_IF_ERROR(change_op_shape(condition->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(condition->parameter_instruction(0)).status()); if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); PrintSubexpression(condition->root_instruction(), /*depth=*/3); } const int loop_bound = GetLoopBoundWithOuterLoopMax( *while_hlo, call_graph, while_execution_count_, max_outer_loop_count_, max_loop_count_); VLOG(1) << "loop_bound = " << loop_bound; HloInstruction* limit = condition->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(loop_bound))); Shape shape = initialization->shape(); HloInstruction* induction_variable = condition->AddInstruction(HloInstruction::CreateGetTupleElement( shape, condition->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* compare = condition->AddInstruction(HloInstruction::CreateCompare( ShapeUtil::MakeShape(PRED, {}), induction_variable, limit, ComparisonDirection::kLt)); TF_RETURN_IF_ERROR( condition->ReplaceInstruction(condition->root_instruction(), compare)); } { // Add the new variable to the while loop body. HloComputation* body = while_hlo->while_body(); TF_RETURN_IF_ERROR(change_op_shape(body->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(body->parameter_instruction(0)).status()); HloInstruction* old_root = body->root_instruction(); Shape shape = initialization->shape(); HloInstruction* induction_variable = body->AddInstruction(HloInstruction::CreateGetTupleElement( shape, body->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* increment = body->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(1))); induction_variable = body->AddInstruction(HloInstruction::CreateBinary( shape, HloOpcode::kAdd, induction_variable, increment)); HloInstruction* new_root = TupleUtil::AppendSuffix(old_root, {induction_variable}); body->set_root_instruction(new_root, /*accept_different_shape=*/true); } // Snapshot the users of while hlo before we add new users. std::vector<HloInstruction*> while_users(while_hlo->users().begin(), while_hlo->users().end()); // Take care of the users of this while loop. TF_RETURN_IF_ERROR(change_op_shape(while_hlo)); TF_ASSIGN_OR_RETURN(HloInstruction * prefix, replace_non_gte_users(while_hlo)); // If the while loop had been the root of its computation, make the prefix new // root. if (while_hlo->parent()->root_instruction() == while_hlo) { // We need to set accept_different_shape=true to reset the root shape to the // original, because we have already changed the shape of the old root // (while). if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix(while_hlo, new_tuple_size - 1); } while_hlo->parent()->set_root_instruction(prefix, /*accept_different_shape=*/true); } return absl::OkStatus(); } auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); VLOG(1) << "loop_bound = " << loop_bound; absl::Status HloControlFlowFlattening::RemoveInfeed( HloInstruction* infeed_hlo) const { CHECK_EQ(infeed_hlo->opcode(), HloOpcode::kInfeed); HloComputation* computation = infeed_hlo->parent(); CHECK_EQ(infeed_hlo->shape().tuple_shapes_size(), 2); const Shape& infeed_shape = ShapeUtil::GetSubshape(infeed_hlo->shape(), {0}); HloInstruction* custom_call = computation->AddInstruction( HloInstruction::CreateCustomCall(infeed_shape, {}, kNopCustomCallTarget)); // Create a new tuple consisting of the constant and the token that was // originally the operand of infeed, and replace the infeed operation. auto new_tuple = HloInstruction::CreateTuple( {custom_call, infeed_hlo->mutable_operand(0)}); TF_RETURN_IF_ERROR( computation->ReplaceWithNewInstruction(infeed_hlo, std::move(new_tuple))); custom_call->SetAndSanitizeName(infeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveRecvAndRecvDone( HloInstruction* recv_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(recv_done->opcode(), HloOpcode::kRecvDone); CHECK_EQ(recv_done->operand_count(), 1); HloInstruction* recv = recv_done->mutable_operand(0); CHECK_EQ(recv->opcode(), HloOpcode::kRecv); HloComputation* computation = recv_done->parent(); CHECK_EQ(recv_done->shape().tuple_shapes_size(), 2); HloModule* module = computation->parent(); HloInstruction* custom_call_recv = computation->AddInstruction(HloInstruction::CreateCustomCall( recv->shape(), recv->operands(), kNopCustomCallTarget)); std::string original_recv_name(recv->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv, custom_call_recv); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(recv, custom_call_recv)); custom_call_recv->SetAndSanitizeName(original_recv_name); std::string original_recv_done_name(recv_done->name()); HloInstruction* custom_call_recv_done = computation->AddInstruction( HloInstruction::CreateCustomCall( recv_done->shape(), recv_done->operands(), kNopCustomCallTarget), recv_done->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv_done, custom_call_recv_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(recv_done, custom_call_recv_done)); custom_call_recv_done->SetAndSanitizeName(original_recv_done_name); return std::make_pair(custom_call_recv, custom_call_recv_done); } absl::Status HloControlFlowFlattening::RemoveOutfeed( HloInstruction* outfeed_hlo) const { CHECK_EQ(outfeed_hlo->opcode(), HloOpcode::kOutfeed); HloComputation* computation = outfeed_hlo->parent(); // Replace the outfeed with a no-op custom call with side effect to ensure the // operands aren't DCE'd. HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( outfeed_hlo->shape(), outfeed_hlo->operands(), kNopReturnTokenCustomCallTarget)); Cast<HloCustomCallInstruction>(custom_call) ->set_custom_call_has_side_effect(true); // For SPMD graphs, partitioner requires that side-effecting custom calls have // a sharding that is non-replicated. custom_call->set_sharding(HloSharding::Manual()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(outfeed_hlo, custom_call)); custom_call->SetAndSanitizeName(outfeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveSendAndSendDone( HloInstruction* send_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(send_done->opcode(), HloOpcode::kSendDone); CHECK_EQ(send_done->operand_count(), 1); HloInstruction* send = send_done->mutable_operand(0); CHECK_EQ(send->opcode(), HloOpcode::kSend); HloComputation* computation = send_done->parent(); HloModule* module = computation->parent(); HloInstruction* custom_call_send = computation->AddInstruction(HloInstruction::CreateCustomCall( send->shape(), send->operands(), kNopCustomCallTarget)); std::string original_send_name(send->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send, custom_call_send); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(send, custom_call_send)); custom_call_send->SetAndSanitizeName(original_send_name); HloInstruction* custom_call_send_done = computation->AddInstruction(HloInstruction::CreateCustomCall( send_done->shape(), send_done->operands(), kNopReturnTokenCustomCallTarget)); std::string original_send_done_name(send_done->name()); Cast<HloCustomCallInstruction>(custom_call_send_done) ->set_custom_call_has_side_effect(true); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send_done, custom_call_send_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(send_done, custom_call_send_done)); custom_call_send_done->SetAndSanitizeName(original_send_done_name); return std::make_pair(custom_call_send, custom_call_send_done); } absl::StatusOr<HloInstruction*> HloControlFlowFlattening::RemoveCollective( HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( hlo->shape(), hlo->operands(), kNopCustomCallTarget)); // Copy backend config. This is necessary for a collective op in megacore // fusion. custom_call->CopyBackendConfigFrom(hlo); HloModule* module = computation->parent(); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, hlo, custom_call); } std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, custom_call)); custom_call->SetAndSanitizeName(original_op_name); return custom_call; } absl::Status HloControlFlowFlattening::RemoveId(HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* zero = CreateConstant(hlo->shape(), computation); std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, zero)); zero->SetAndSanitizeName(original_op_name); return absl::OkStatus(); } absl::StatusOr<bool> HloControlFlowFlattening::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { auto call_graph = CallGraph::Build(module); bool changed = false; absl::flat_hash_set<HloInstruction*> removed; for (HloComputation* computation : module->computations(execution_threads)) { // Do not change computations that are wrapped by async calls. Instead we // remove the async callers if needed. if (computation->IsAsyncComputation()) { continue; } for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (removed.contains(instruction)) { // Skip the instruction if it is already removed. continue; } if (flatten_while_loop_ && instruction->opcode() == HloOpcode::kWhile) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(FlattenWhileLoop(instruction, *call_graph)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kInfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveInfeed(instruction)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kOutfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveOutfeed(instruction)); changed = true; } else if (instruction->opcode() == HloOpcode::kSendDone) { auto send_done_instruction = DynCast<HloSendDoneInstruction>(instruction); CHECK(send_done_instruction); if (remove_comm_ || (remove_host_transfer_ && send_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveSendAndSendDone(instruction, &removed).status()); changed = true; } } else if (instruction->opcode() == HloOpcode::kRecvDone) { auto recv_done_instruction = DynCast<HloRecvDoneInstruction>(instruction); CHECK(recv_done_instruction); if (remove_comm_ || (remove_host_transfer_ && recv_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveRecvAndRecvDone(instruction, &removed).status()); changed = true; } } else if (remove_comm_ && IsCollective(instruction) && !instruction->parent()->IsFusionComputation() && (instruction->opcode() != HloOpcode::kAsyncStart && instruction->opcode() != HloOpcode::kAsyncUpdate)) { // We do not remove kAsyncStart or kAsyncUpdate here since we expect // them to be removed as a part of the async chain above. // We should remove the async chain all together because the async // wrapped computation is only associated with the AsyncStart. So we // need to refer to the AsyncStart in order to determine whether // the Done or the Update wraps a collective. if (instruction->opcode() == HloOpcode::kAsyncDone) { while (instruction->opcode() == HloOpcode::kAsyncDone || instruction->opcode() == HloOpcode::kAsyncUpdate || instruction->opcode() == HloOpcode::kAsyncStart) { HloInstruction* operand = instruction->mutable_operand(0); VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); instruction = operand; } } else { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); } changed = true; } else if (remove_comm_ && (instruction->opcode() == HloOpcode::kPartitionId || instruction->opcode() == HloOpcode::kReplicaId || (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == "SliceId"))) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveId(instruction)); changed = true; } } } HloDCE hlo_dce; TF_ASSIGN_OR_RETURN(bool dce_changed, hlo_dce.Run(module, execution_threads)); changed |= dce_changed; // Fix the schedule if the module was scheduled. if (changed && module->has_schedule()) { TF_RETURN_IF_ERROR(module->schedule().Update()); } XLA_VLOG_LINES(3, module->ToString()); return changed; } VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); XLA_VLOG_LINES(3, module->ToString());
#include "xla/tools/hlo_control_flow_flattening.h" #include <memory> #include <utility> #include "absl/strings/str_replace.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/collective_ops_utils.h" #include "xla/service/despecializer.h" #include "xla/service/hlo_verifier.h" #include "xla/service/spmd/spmd_partitioner.h" #include "xla/tests/hlo_test_base.h" #include "tsl/lib/core/status_test_util.h" class HloControlFlowFlatteningTest : public HloTestBase { public: absl::StatusOr<std::unique_ptr<HloModule>> PartitionComputation( std::unique_ptr<VerifiedHloModule> hlo_module, int64_t num_devices = 2) { spmd::SpmdPartitionerOptions options; auto collective_ops_creator = spmd::GetDefaultCollectiveOpsCreator(num_devices, /*num_replicas=*/1); collective_ops_creator.create_cross_partition_all_gather = nullptr; HloModuleConfig config = GetModuleConfigForTest(); config.set_use_spmd_partitioning(true); config.set_num_partitions(num_devices); HloPassPipeline pass("spmd-partitioning"); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); pass.AddPass<spmd::SpmdPartitioner>(num_devices, /*num_replicas=*/1, options, collective_ops_creator); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); TF_RETURN_IF_ERROR(pass.Run(hlo_module.get()).status()); return absl::StatusOr<std::unique_ptr<HloModule>>(std::move(hlo_module)); } }; TEST_F(HloControlFlowFlatteningTest, Outfeed) { absl::string_view hlo_string = R"( HloModule Outfeed ENTRY Outfeed { param = (bf16[3]{0}, s32[12,5]{0,1}) parameter(0) after-all = token[] after-all() ROOT outfeed.23 = token[] outfeed(param, after-all) } )"; TF_ASSERT_OK_AND_ASSIGN(auto module, ParseAndReturnVerifiedModule(hlo_string)); HloControlFlowFlattening flattening( HloControlFlowFlattening::Options{/*while_execution_count=*/3}); EXPECT_TRUE(flattening.Run(module.get()).value()); TF_ASSERT_OK(HloVerifier(/*layout_sensitive=*/true, /*allow_mixed_precision=*/true) .Run(module.get()) .status()); auto custom_call = module->entry_computation()->root_instruction(); EXPECT_EQ(custom_call->name(), "outfeed.23"); EXPECT_THAT(custom_call, op::CustomCall(op::Parameter(0), op::AfterAll())); }
HloControlFlowFlatteningTest_OutfeedCustomCallIsPartitionable
xla/tools/hlo_control_flow_flattening_test.cc
HloInstruction* CreateConstant(const Shape& shape, HloComputation* computation) { if (shape.IsTuple()) { std::vector<HloInstruction*> tuple_arguments(shape.tuple_shapes_size()); for (int index = 0; index < shape.tuple_shapes_size(); ++index) { tuple_arguments[index] = CreateConstant(shape.tuple_shapes(index), computation); } return computation->AddInstruction( HloInstruction::CreateTuple(tuple_arguments)); } else { return computation->AddInstruction( HloInstruction::CreateConstant(Literal::CreateFromShape(shape))); } } void PrintSubexpression(HloInstruction* inst, int depth) { if (depth == 0) { return; } for (auto* operand : inst->operands()) { PrintSubexpression(operand, depth - 1); } VLOG(2) << inst->ToString(); } VLOG(2) << inst->ToString(); bool IsConstantScalarInt(const HloInstruction* inst) { return inst->opcode() == HloOpcode::kConstant && ShapeUtil::IsEffectiveScalar(inst->shape()) && inst->shape().IsInteger(); } bool IsNotContainedInLoop(const HloInstruction& while_hlo, const CallGraph& call_graph) { const HloComputation* computation = while_hlo.parent(); while (!computation->IsEntryComputation()) { auto& node = call_graph.GetNode(computation); CHECK_EQ(node.caller_callsites().size(), 1) << "The module is not flattened!"; auto& callsite = node.caller_callsites()[0]; if (callsite.instruction()->opcode() == HloOpcode::kWhile) { // Another while loop has been found traversing up the call tree. return false; } computation = callsite.instruction()->parent(); } // No calling while loops were found. return true; } int GetLoopBound(const HloInstruction& while_hlo, const int default_loop_count, const int max_loop_count) { HloInstruction* condition = while_hlo.while_condition()->root_instruction(); if (condition->opcode() == HloOpcode::kCompare) { int64_t value = 0; Comparison::Direction cmp = condition->comparison_direction(); if ((cmp == Comparison::Direction::kLt || cmp == Comparison::Direction::kLe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(1))) { value = *condition->operand(1)->literal().GetFirstInteger(); } else if ((cmp == Comparison::Direction::kGt || cmp == Comparison::Direction::kGe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(0))) { value = *condition->operand(0)->literal().GetFirstInteger(); } if (value > 0) { // Caps to a max loop count to avoid long execution times. return std::min(value, static_cast<int64_t>(max_loop_count)); } } return default_loop_count; } int GetLoopBoundWithOuterLoopMax(const HloInstruction& while_hlo, const CallGraph& call_graph, const int default_loop_count, const int max_outer_loop_count, const int max_loop_count) { int loop_bound = GetLoopBound(while_hlo, default_loop_count, max_loop_count); if (loop_bound > max_outer_loop_count) { // First does the inexpensive loop bound check to avoid as many // expensive graph traversals in IsNotContainedInLoop as possible. if (IsNotContainedInLoop(while_hlo, call_graph)) { return max_outer_loop_count; } } return loop_bound; } absl::Status HloControlFlowFlattening::FlattenWhileLoop( HloInstruction* while_hlo, const CallGraph& call_graph) const { CHECK_EQ(while_hlo->opcode(), HloOpcode::kWhile); HloComputation* computation = while_hlo->parent(); // Add a new induction variable. HloInstruction* initialization = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(0))); // Create a new while operand with the induction variable added. HloInstruction* old_tuple = while_hlo->mutable_operand(0); HloInstruction* new_tuple = TupleUtil::AppendSuffix(old_tuple, {initialization}); int new_tuple_size = new_tuple->shape().tuple_shapes().size(); TF_RETURN_IF_ERROR(while_hlo->ReplaceOperandWithDifferentShape(0, new_tuple)); auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; // Replace the given tuple-shaped instruction of size N in each of its // non-get-tuple-element users with a new tuple instruction which has the // first N - 1 elements. auto replace_non_gte_users = [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; { // Add the new variable to the while loop condition. HloComputation* condition = while_hlo->while_condition(); TF_RETURN_IF_ERROR(change_op_shape(condition->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(condition->parameter_instruction(0)).status()); if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); PrintSubexpression(condition->root_instruction(), /*depth=*/3); } const int loop_bound = GetLoopBoundWithOuterLoopMax( *while_hlo, call_graph, while_execution_count_, max_outer_loop_count_, max_loop_count_); VLOG(1) << "loop_bound = " << loop_bound; HloInstruction* limit = condition->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(loop_bound))); Shape shape = initialization->shape(); HloInstruction* induction_variable = condition->AddInstruction(HloInstruction::CreateGetTupleElement( shape, condition->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* compare = condition->AddInstruction(HloInstruction::CreateCompare( ShapeUtil::MakeShape(PRED, {}), induction_variable, limit, ComparisonDirection::kLt)); TF_RETURN_IF_ERROR( condition->ReplaceInstruction(condition->root_instruction(), compare)); } { // Add the new variable to the while loop body. HloComputation* body = while_hlo->while_body(); TF_RETURN_IF_ERROR(change_op_shape(body->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(body->parameter_instruction(0)).status()); HloInstruction* old_root = body->root_instruction(); Shape shape = initialization->shape(); HloInstruction* induction_variable = body->AddInstruction(HloInstruction::CreateGetTupleElement( shape, body->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* increment = body->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(1))); induction_variable = body->AddInstruction(HloInstruction::CreateBinary( shape, HloOpcode::kAdd, induction_variable, increment)); HloInstruction* new_root = TupleUtil::AppendSuffix(old_root, {induction_variable}); body->set_root_instruction(new_root, /*accept_different_shape=*/true); } // Snapshot the users of while hlo before we add new users. std::vector<HloInstruction*> while_users(while_hlo->users().begin(), while_hlo->users().end()); // Take care of the users of this while loop. TF_RETURN_IF_ERROR(change_op_shape(while_hlo)); TF_ASSIGN_OR_RETURN(HloInstruction * prefix, replace_non_gte_users(while_hlo)); // If the while loop had been the root of its computation, make the prefix new // root. if (while_hlo->parent()->root_instruction() == while_hlo) { // We need to set accept_different_shape=true to reset the root shape to the // original, because we have already changed the shape of the old root // (while). if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix(while_hlo, new_tuple_size - 1); } while_hlo->parent()->set_root_instruction(prefix, /*accept_different_shape=*/true); } return absl::OkStatus(); } auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); VLOG(1) << "loop_bound = " << loop_bound; absl::Status HloControlFlowFlattening::RemoveInfeed( HloInstruction* infeed_hlo) const { CHECK_EQ(infeed_hlo->opcode(), HloOpcode::kInfeed); HloComputation* computation = infeed_hlo->parent(); CHECK_EQ(infeed_hlo->shape().tuple_shapes_size(), 2); const Shape& infeed_shape = ShapeUtil::GetSubshape(infeed_hlo->shape(), {0}); HloInstruction* custom_call = computation->AddInstruction( HloInstruction::CreateCustomCall(infeed_shape, {}, kNopCustomCallTarget)); // Create a new tuple consisting of the constant and the token that was // originally the operand of infeed, and replace the infeed operation. auto new_tuple = HloInstruction::CreateTuple( {custom_call, infeed_hlo->mutable_operand(0)}); TF_RETURN_IF_ERROR( computation->ReplaceWithNewInstruction(infeed_hlo, std::move(new_tuple))); custom_call->SetAndSanitizeName(infeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveRecvAndRecvDone( HloInstruction* recv_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(recv_done->opcode(), HloOpcode::kRecvDone); CHECK_EQ(recv_done->operand_count(), 1); HloInstruction* recv = recv_done->mutable_operand(0); CHECK_EQ(recv->opcode(), HloOpcode::kRecv); HloComputation* computation = recv_done->parent(); CHECK_EQ(recv_done->shape().tuple_shapes_size(), 2); HloModule* module = computation->parent(); HloInstruction* custom_call_recv = computation->AddInstruction(HloInstruction::CreateCustomCall( recv->shape(), recv->operands(), kNopCustomCallTarget)); std::string original_recv_name(recv->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv, custom_call_recv); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(recv, custom_call_recv)); custom_call_recv->SetAndSanitizeName(original_recv_name); std::string original_recv_done_name(recv_done->name()); HloInstruction* custom_call_recv_done = computation->AddInstruction( HloInstruction::CreateCustomCall( recv_done->shape(), recv_done->operands(), kNopCustomCallTarget), recv_done->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv_done, custom_call_recv_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(recv_done, custom_call_recv_done)); custom_call_recv_done->SetAndSanitizeName(original_recv_done_name); return std::make_pair(custom_call_recv, custom_call_recv_done); } absl::Status HloControlFlowFlattening::RemoveOutfeed( HloInstruction* outfeed_hlo) const { CHECK_EQ(outfeed_hlo->opcode(), HloOpcode::kOutfeed); HloComputation* computation = outfeed_hlo->parent(); // Replace the outfeed with a no-op custom call with side effect to ensure the // operands aren't DCE'd. HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( outfeed_hlo->shape(), outfeed_hlo->operands(), kNopReturnTokenCustomCallTarget)); Cast<HloCustomCallInstruction>(custom_call) ->set_custom_call_has_side_effect(true); // For SPMD graphs, partitioner requires that side-effecting custom calls have // a sharding that is non-replicated. custom_call->set_sharding(HloSharding::Manual()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(outfeed_hlo, custom_call)); custom_call->SetAndSanitizeName(outfeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveSendAndSendDone( HloInstruction* send_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(send_done->opcode(), HloOpcode::kSendDone); CHECK_EQ(send_done->operand_count(), 1); HloInstruction* send = send_done->mutable_operand(0); CHECK_EQ(send->opcode(), HloOpcode::kSend); HloComputation* computation = send_done->parent(); HloModule* module = computation->parent(); HloInstruction* custom_call_send = computation->AddInstruction(HloInstruction::CreateCustomCall( send->shape(), send->operands(), kNopCustomCallTarget)); std::string original_send_name(send->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send, custom_call_send); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(send, custom_call_send)); custom_call_send->SetAndSanitizeName(original_send_name); HloInstruction* custom_call_send_done = computation->AddInstruction(HloInstruction::CreateCustomCall( send_done->shape(), send_done->operands(), kNopReturnTokenCustomCallTarget)); std::string original_send_done_name(send_done->name()); Cast<HloCustomCallInstruction>(custom_call_send_done) ->set_custom_call_has_side_effect(true); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send_done, custom_call_send_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(send_done, custom_call_send_done)); custom_call_send_done->SetAndSanitizeName(original_send_done_name); return std::make_pair(custom_call_send, custom_call_send_done); } absl::StatusOr<HloInstruction*> HloControlFlowFlattening::RemoveCollective( HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( hlo->shape(), hlo->operands(), kNopCustomCallTarget)); // Copy backend config. This is necessary for a collective op in megacore // fusion. custom_call->CopyBackendConfigFrom(hlo); HloModule* module = computation->parent(); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, hlo, custom_call); } std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, custom_call)); custom_call->SetAndSanitizeName(original_op_name); return custom_call; } absl::Status HloControlFlowFlattening::RemoveId(HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* zero = CreateConstant(hlo->shape(), computation); std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, zero)); zero->SetAndSanitizeName(original_op_name); return absl::OkStatus(); } absl::StatusOr<bool> HloControlFlowFlattening::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { auto call_graph = CallGraph::Build(module); bool changed = false; absl::flat_hash_set<HloInstruction*> removed; for (HloComputation* computation : module->computations(execution_threads)) { // Do not change computations that are wrapped by async calls. Instead we // remove the async callers if needed. if (computation->IsAsyncComputation()) { continue; } for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (removed.contains(instruction)) { // Skip the instruction if it is already removed. continue; } if (flatten_while_loop_ && instruction->opcode() == HloOpcode::kWhile) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(FlattenWhileLoop(instruction, *call_graph)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kInfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveInfeed(instruction)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kOutfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveOutfeed(instruction)); changed = true; } else if (instruction->opcode() == HloOpcode::kSendDone) { auto send_done_instruction = DynCast<HloSendDoneInstruction>(instruction); CHECK(send_done_instruction); if (remove_comm_ || (remove_host_transfer_ && send_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveSendAndSendDone(instruction, &removed).status()); changed = true; } } else if (instruction->opcode() == HloOpcode::kRecvDone) { auto recv_done_instruction = DynCast<HloRecvDoneInstruction>(instruction); CHECK(recv_done_instruction); if (remove_comm_ || (remove_host_transfer_ && recv_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveRecvAndRecvDone(instruction, &removed).status()); changed = true; } } else if (remove_comm_ && IsCollective(instruction) && !instruction->parent()->IsFusionComputation() && (instruction->opcode() != HloOpcode::kAsyncStart && instruction->opcode() != HloOpcode::kAsyncUpdate)) { // We do not remove kAsyncStart or kAsyncUpdate here since we expect // them to be removed as a part of the async chain above. // We should remove the async chain all together because the async // wrapped computation is only associated with the AsyncStart. So we // need to refer to the AsyncStart in order to determine whether // the Done or the Update wraps a collective. if (instruction->opcode() == HloOpcode::kAsyncDone) { while (instruction->opcode() == HloOpcode::kAsyncDone || instruction->opcode() == HloOpcode::kAsyncUpdate || instruction->opcode() == HloOpcode::kAsyncStart) { HloInstruction* operand = instruction->mutable_operand(0); VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); instruction = operand; } } else { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); } changed = true; } else if (remove_comm_ && (instruction->opcode() == HloOpcode::kPartitionId || instruction->opcode() == HloOpcode::kReplicaId || (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == "SliceId"))) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveId(instruction)); changed = true; } } } HloDCE hlo_dce; TF_ASSIGN_OR_RETURN(bool dce_changed, hlo_dce.Run(module, execution_threads)); changed |= dce_changed; // Fix the schedule if the module was scheduled. if (changed && module->has_schedule()) { TF_RETURN_IF_ERROR(module->schedule().Update()); } XLA_VLOG_LINES(3, module->ToString()); return changed; } VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); XLA_VLOG_LINES(3, module->ToString());
#include "xla/tools/hlo_control_flow_flattening.h" #include <memory> #include <utility> #include "absl/strings/str_replace.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/collective_ops_utils.h" #include "xla/service/despecializer.h" #include "xla/service/hlo_verifier.h" #include "xla/service/spmd/spmd_partitioner.h" #include "xla/tests/hlo_test_base.h" #include "tsl/lib/core/status_test_util.h" class HloControlFlowFlatteningTest : public HloTestBase { public: absl::StatusOr<std::unique_ptr<HloModule>> PartitionComputation( std::unique_ptr<VerifiedHloModule> hlo_module, int64_t num_devices = 2) { spmd::SpmdPartitionerOptions options; auto collective_ops_creator = spmd::GetDefaultCollectiveOpsCreator(num_devices, /*num_replicas=*/1); collective_ops_creator.create_cross_partition_all_gather = nullptr; HloModuleConfig config = GetModuleConfigForTest(); config.set_use_spmd_partitioning(true); config.set_num_partitions(num_devices); HloPassPipeline pass("spmd-partitioning"); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); pass.AddPass<spmd::SpmdPartitioner>(num_devices, /*num_replicas=*/1, options, collective_ops_creator); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); TF_RETURN_IF_ERROR(pass.Run(hlo_module.get()).status()); return absl::StatusOr<std::unique_ptr<HloModule>>(std::move(hlo_module)); } }; TEST_F(HloControlFlowFlatteningTest, OutfeedCustomCallIsPartitionable) { absl::string_view hlo_string = R"( HloModule Outfeed ENTRY Outfeed { param = (bf16[3]{0}, s32[12,5]{0,1}) parameter(0) after-all = token[] after-all() ROOT outfeed.23 = token[] outfeed(param, after-all) } )"; TF_ASSERT_OK_AND_ASSIGN(auto module, ParseAndReturnVerifiedModule(hlo_string)); HloControlFlowFlattening flattening(HloControlFlowFlattening::Options{ /*while_execution_count=*/3, /*max_outer_loop_count=*/3, /*max_loop_count=*/3, /*remove_infeed_outfeed=*/true}); EXPECT_TRUE(flattening.Run(module.get()).value()); auto custom_call = module->entry_computation()->root_instruction(); EXPECT_EQ(custom_call->name(), "outfeed.23"); EXPECT_TRUE(custom_call->has_sharding()); TF_ASSERT_OK_AND_ASSIGN(auto hlo_module, PartitionComputation(std::move(module))); }
HloControlFlowFlatteningTest_Recv
xla/tools/hlo_control_flow_flattening_test.cc
HloInstruction* CreateConstant(const Shape& shape, HloComputation* computation) { if (shape.IsTuple()) { std::vector<HloInstruction*> tuple_arguments(shape.tuple_shapes_size()); for (int index = 0; index < shape.tuple_shapes_size(); ++index) { tuple_arguments[index] = CreateConstant(shape.tuple_shapes(index), computation); } return computation->AddInstruction( HloInstruction::CreateTuple(tuple_arguments)); } else { return computation->AddInstruction( HloInstruction::CreateConstant(Literal::CreateFromShape(shape))); } } void PrintSubexpression(HloInstruction* inst, int depth) { if (depth == 0) { return; } for (auto* operand : inst->operands()) { PrintSubexpression(operand, depth - 1); } VLOG(2) << inst->ToString(); } VLOG(2) << inst->ToString(); bool IsConstantScalarInt(const HloInstruction* inst) { return inst->opcode() == HloOpcode::kConstant && ShapeUtil::IsEffectiveScalar(inst->shape()) && inst->shape().IsInteger(); } bool IsNotContainedInLoop(const HloInstruction& while_hlo, const CallGraph& call_graph) { const HloComputation* computation = while_hlo.parent(); while (!computation->IsEntryComputation()) { auto& node = call_graph.GetNode(computation); CHECK_EQ(node.caller_callsites().size(), 1) << "The module is not flattened!"; auto& callsite = node.caller_callsites()[0]; if (callsite.instruction()->opcode() == HloOpcode::kWhile) { // Another while loop has been found traversing up the call tree. return false; } computation = callsite.instruction()->parent(); } // No calling while loops were found. return true; } int GetLoopBound(const HloInstruction& while_hlo, const int default_loop_count, const int max_loop_count) { HloInstruction* condition = while_hlo.while_condition()->root_instruction(); if (condition->opcode() == HloOpcode::kCompare) { int64_t value = 0; Comparison::Direction cmp = condition->comparison_direction(); if ((cmp == Comparison::Direction::kLt || cmp == Comparison::Direction::kLe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(1))) { value = *condition->operand(1)->literal().GetFirstInteger(); } else if ((cmp == Comparison::Direction::kGt || cmp == Comparison::Direction::kGe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(0))) { value = *condition->operand(0)->literal().GetFirstInteger(); } if (value > 0) { // Caps to a max loop count to avoid long execution times. return std::min(value, static_cast<int64_t>(max_loop_count)); } } return default_loop_count; } int GetLoopBoundWithOuterLoopMax(const HloInstruction& while_hlo, const CallGraph& call_graph, const int default_loop_count, const int max_outer_loop_count, const int max_loop_count) { int loop_bound = GetLoopBound(while_hlo, default_loop_count, max_loop_count); if (loop_bound > max_outer_loop_count) { // First does the inexpensive loop bound check to avoid as many // expensive graph traversals in IsNotContainedInLoop as possible. if (IsNotContainedInLoop(while_hlo, call_graph)) { return max_outer_loop_count; } } return loop_bound; } absl::Status HloControlFlowFlattening::FlattenWhileLoop( HloInstruction* while_hlo, const CallGraph& call_graph) const { CHECK_EQ(while_hlo->opcode(), HloOpcode::kWhile); HloComputation* computation = while_hlo->parent(); // Add a new induction variable. HloInstruction* initialization = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(0))); // Create a new while operand with the induction variable added. HloInstruction* old_tuple = while_hlo->mutable_operand(0); HloInstruction* new_tuple = TupleUtil::AppendSuffix(old_tuple, {initialization}); int new_tuple_size = new_tuple->shape().tuple_shapes().size(); TF_RETURN_IF_ERROR(while_hlo->ReplaceOperandWithDifferentShape(0, new_tuple)); auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; // Replace the given tuple-shaped instruction of size N in each of its // non-get-tuple-element users with a new tuple instruction which has the // first N - 1 elements. auto replace_non_gte_users = [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; { // Add the new variable to the while loop condition. HloComputation* condition = while_hlo->while_condition(); TF_RETURN_IF_ERROR(change_op_shape(condition->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(condition->parameter_instruction(0)).status()); if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); PrintSubexpression(condition->root_instruction(), /*depth=*/3); } const int loop_bound = GetLoopBoundWithOuterLoopMax( *while_hlo, call_graph, while_execution_count_, max_outer_loop_count_, max_loop_count_); VLOG(1) << "loop_bound = " << loop_bound; HloInstruction* limit = condition->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(loop_bound))); Shape shape = initialization->shape(); HloInstruction* induction_variable = condition->AddInstruction(HloInstruction::CreateGetTupleElement( shape, condition->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* compare = condition->AddInstruction(HloInstruction::CreateCompare( ShapeUtil::MakeShape(PRED, {}), induction_variable, limit, ComparisonDirection::kLt)); TF_RETURN_IF_ERROR( condition->ReplaceInstruction(condition->root_instruction(), compare)); } { // Add the new variable to the while loop body. HloComputation* body = while_hlo->while_body(); TF_RETURN_IF_ERROR(change_op_shape(body->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(body->parameter_instruction(0)).status()); HloInstruction* old_root = body->root_instruction(); Shape shape = initialization->shape(); HloInstruction* induction_variable = body->AddInstruction(HloInstruction::CreateGetTupleElement( shape, body->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* increment = body->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(1))); induction_variable = body->AddInstruction(HloInstruction::CreateBinary( shape, HloOpcode::kAdd, induction_variable, increment)); HloInstruction* new_root = TupleUtil::AppendSuffix(old_root, {induction_variable}); body->set_root_instruction(new_root, /*accept_different_shape=*/true); } // Snapshot the users of while hlo before we add new users. std::vector<HloInstruction*> while_users(while_hlo->users().begin(), while_hlo->users().end()); // Take care of the users of this while loop. TF_RETURN_IF_ERROR(change_op_shape(while_hlo)); TF_ASSIGN_OR_RETURN(HloInstruction * prefix, replace_non_gte_users(while_hlo)); // If the while loop had been the root of its computation, make the prefix new // root. if (while_hlo->parent()->root_instruction() == while_hlo) { // We need to set accept_different_shape=true to reset the root shape to the // original, because we have already changed the shape of the old root // (while). if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix(while_hlo, new_tuple_size - 1); } while_hlo->parent()->set_root_instruction(prefix, /*accept_different_shape=*/true); } return absl::OkStatus(); } auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); VLOG(1) << "loop_bound = " << loop_bound; absl::Status HloControlFlowFlattening::RemoveInfeed( HloInstruction* infeed_hlo) const { CHECK_EQ(infeed_hlo->opcode(), HloOpcode::kInfeed); HloComputation* computation = infeed_hlo->parent(); CHECK_EQ(infeed_hlo->shape().tuple_shapes_size(), 2); const Shape& infeed_shape = ShapeUtil::GetSubshape(infeed_hlo->shape(), {0}); HloInstruction* custom_call = computation->AddInstruction( HloInstruction::CreateCustomCall(infeed_shape, {}, kNopCustomCallTarget)); // Create a new tuple consisting of the constant and the token that was // originally the operand of infeed, and replace the infeed operation. auto new_tuple = HloInstruction::CreateTuple( {custom_call, infeed_hlo->mutable_operand(0)}); TF_RETURN_IF_ERROR( computation->ReplaceWithNewInstruction(infeed_hlo, std::move(new_tuple))); custom_call->SetAndSanitizeName(infeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveRecvAndRecvDone( HloInstruction* recv_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(recv_done->opcode(), HloOpcode::kRecvDone); CHECK_EQ(recv_done->operand_count(), 1); HloInstruction* recv = recv_done->mutable_operand(0); CHECK_EQ(recv->opcode(), HloOpcode::kRecv); HloComputation* computation = recv_done->parent(); CHECK_EQ(recv_done->shape().tuple_shapes_size(), 2); HloModule* module = computation->parent(); HloInstruction* custom_call_recv = computation->AddInstruction(HloInstruction::CreateCustomCall( recv->shape(), recv->operands(), kNopCustomCallTarget)); std::string original_recv_name(recv->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv, custom_call_recv); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(recv, custom_call_recv)); custom_call_recv->SetAndSanitizeName(original_recv_name); std::string original_recv_done_name(recv_done->name()); HloInstruction* custom_call_recv_done = computation->AddInstruction( HloInstruction::CreateCustomCall( recv_done->shape(), recv_done->operands(), kNopCustomCallTarget), recv_done->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv_done, custom_call_recv_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(recv_done, custom_call_recv_done)); custom_call_recv_done->SetAndSanitizeName(original_recv_done_name); return std::make_pair(custom_call_recv, custom_call_recv_done); } absl::Status HloControlFlowFlattening::RemoveOutfeed( HloInstruction* outfeed_hlo) const { CHECK_EQ(outfeed_hlo->opcode(), HloOpcode::kOutfeed); HloComputation* computation = outfeed_hlo->parent(); // Replace the outfeed with a no-op custom call with side effect to ensure the // operands aren't DCE'd. HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( outfeed_hlo->shape(), outfeed_hlo->operands(), kNopReturnTokenCustomCallTarget)); Cast<HloCustomCallInstruction>(custom_call) ->set_custom_call_has_side_effect(true); // For SPMD graphs, partitioner requires that side-effecting custom calls have // a sharding that is non-replicated. custom_call->set_sharding(HloSharding::Manual()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(outfeed_hlo, custom_call)); custom_call->SetAndSanitizeName(outfeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveSendAndSendDone( HloInstruction* send_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(send_done->opcode(), HloOpcode::kSendDone); CHECK_EQ(send_done->operand_count(), 1); HloInstruction* send = send_done->mutable_operand(0); CHECK_EQ(send->opcode(), HloOpcode::kSend); HloComputation* computation = send_done->parent(); HloModule* module = computation->parent(); HloInstruction* custom_call_send = computation->AddInstruction(HloInstruction::CreateCustomCall( send->shape(), send->operands(), kNopCustomCallTarget)); std::string original_send_name(send->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send, custom_call_send); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(send, custom_call_send)); custom_call_send->SetAndSanitizeName(original_send_name); HloInstruction* custom_call_send_done = computation->AddInstruction(HloInstruction::CreateCustomCall( send_done->shape(), send_done->operands(), kNopReturnTokenCustomCallTarget)); std::string original_send_done_name(send_done->name()); Cast<HloCustomCallInstruction>(custom_call_send_done) ->set_custom_call_has_side_effect(true); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send_done, custom_call_send_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(send_done, custom_call_send_done)); custom_call_send_done->SetAndSanitizeName(original_send_done_name); return std::make_pair(custom_call_send, custom_call_send_done); } absl::StatusOr<HloInstruction*> HloControlFlowFlattening::RemoveCollective( HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( hlo->shape(), hlo->operands(), kNopCustomCallTarget)); // Copy backend config. This is necessary for a collective op in megacore // fusion. custom_call->CopyBackendConfigFrom(hlo); HloModule* module = computation->parent(); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, hlo, custom_call); } std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, custom_call)); custom_call->SetAndSanitizeName(original_op_name); return custom_call; } absl::Status HloControlFlowFlattening::RemoveId(HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* zero = CreateConstant(hlo->shape(), computation); std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, zero)); zero->SetAndSanitizeName(original_op_name); return absl::OkStatus(); } absl::StatusOr<bool> HloControlFlowFlattening::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { auto call_graph = CallGraph::Build(module); bool changed = false; absl::flat_hash_set<HloInstruction*> removed; for (HloComputation* computation : module->computations(execution_threads)) { // Do not change computations that are wrapped by async calls. Instead we // remove the async callers if needed. if (computation->IsAsyncComputation()) { continue; } for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (removed.contains(instruction)) { // Skip the instruction if it is already removed. continue; } if (flatten_while_loop_ && instruction->opcode() == HloOpcode::kWhile) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(FlattenWhileLoop(instruction, *call_graph)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kInfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveInfeed(instruction)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kOutfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveOutfeed(instruction)); changed = true; } else if (instruction->opcode() == HloOpcode::kSendDone) { auto send_done_instruction = DynCast<HloSendDoneInstruction>(instruction); CHECK(send_done_instruction); if (remove_comm_ || (remove_host_transfer_ && send_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveSendAndSendDone(instruction, &removed).status()); changed = true; } } else if (instruction->opcode() == HloOpcode::kRecvDone) { auto recv_done_instruction = DynCast<HloRecvDoneInstruction>(instruction); CHECK(recv_done_instruction); if (remove_comm_ || (remove_host_transfer_ && recv_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveRecvAndRecvDone(instruction, &removed).status()); changed = true; } } else if (remove_comm_ && IsCollective(instruction) && !instruction->parent()->IsFusionComputation() && (instruction->opcode() != HloOpcode::kAsyncStart && instruction->opcode() != HloOpcode::kAsyncUpdate)) { // We do not remove kAsyncStart or kAsyncUpdate here since we expect // them to be removed as a part of the async chain above. // We should remove the async chain all together because the async // wrapped computation is only associated with the AsyncStart. So we // need to refer to the AsyncStart in order to determine whether // the Done or the Update wraps a collective. if (instruction->opcode() == HloOpcode::kAsyncDone) { while (instruction->opcode() == HloOpcode::kAsyncDone || instruction->opcode() == HloOpcode::kAsyncUpdate || instruction->opcode() == HloOpcode::kAsyncStart) { HloInstruction* operand = instruction->mutable_operand(0); VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); instruction = operand; } } else { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); } changed = true; } else if (remove_comm_ && (instruction->opcode() == HloOpcode::kPartitionId || instruction->opcode() == HloOpcode::kReplicaId || (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == "SliceId"))) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveId(instruction)); changed = true; } } } HloDCE hlo_dce; TF_ASSIGN_OR_RETURN(bool dce_changed, hlo_dce.Run(module, execution_threads)); changed |= dce_changed; // Fix the schedule if the module was scheduled. if (changed && module->has_schedule()) { TF_RETURN_IF_ERROR(module->schedule().Update()); } XLA_VLOG_LINES(3, module->ToString()); return changed; } VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); XLA_VLOG_LINES(3, module->ToString());
#include "xla/tools/hlo_control_flow_flattening.h" #include <memory> #include <utility> #include "absl/strings/str_replace.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/collective_ops_utils.h" #include "xla/service/despecializer.h" #include "xla/service/hlo_verifier.h" #include "xla/service/spmd/spmd_partitioner.h" #include "xla/tests/hlo_test_base.h" #include "tsl/lib/core/status_test_util.h" class HloControlFlowFlatteningTest : public HloTestBase { public: absl::StatusOr<std::unique_ptr<HloModule>> PartitionComputation( std::unique_ptr<VerifiedHloModule> hlo_module, int64_t num_devices = 2) { spmd::SpmdPartitionerOptions options; auto collective_ops_creator = spmd::GetDefaultCollectiveOpsCreator(num_devices, /*num_replicas=*/1); collective_ops_creator.create_cross_partition_all_gather = nullptr; HloModuleConfig config = GetModuleConfigForTest(); config.set_use_spmd_partitioning(true); config.set_num_partitions(num_devices); HloPassPipeline pass("spmd-partitioning"); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); pass.AddPass<spmd::SpmdPartitioner>(num_devices, /*num_replicas=*/1, options, collective_ops_creator); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); TF_RETURN_IF_ERROR(pass.Run(hlo_module.get()).status()); return absl::StatusOr<std::unique_ptr<HloModule>>(std::move(hlo_module)); } }; TEST_F(HloControlFlowFlatteningTest, Recv) { absl::string_view hlo_string = R"( HloModule Recv ENTRY %Recv () -> (f32[], token[]) { %token0 = token[] after-all() %recv = (f32[], u32[], token[]) recv(token[] %token0), channel_id=15 ROOT %recv-done = (f32[], token[]) recv-done((f32[], u32[], token[]) %recv), channel_id=15 %constant = f32[] constant(2.1) %send = (f32[], u32[], token[]) send(f32[] %constant, token[] %token0), channel_id=16, control-predecessors={%recv} %send-done = token[] send-done((f32[], u32[], token[]) %send), channel_id=16 } )"; TF_ASSERT_OK_AND_ASSIGN(auto module, ParseAndReturnVerifiedModule(hlo_string)); ControlDepRemover control_remover; HloControlFlowFlattening flattening( HloControlFlowFlattening::Options{/*while_execution_count=*/3}); TF_ASSERT_OK(control_remover.Run(module.get()).status()); EXPECT_TRUE(flattening.Run(module.get()).value()); TF_ASSERT_OK(HloVerifier(/*layout_sensitive=*/true, /*allow_mixed_precision=*/true) .Run(module.get()) .status()); EXPECT_THAT(module->entry_computation()->root_instruction(), op::CustomCall(op::CustomCall())); EXPECT_EQ(module->entry_computation()->root_instruction()->name(), "recv-done"); EXPECT_EQ(module->entry_computation()->root_instruction()->operand(0)->name(), "recv"); }
HloControlFlowFlatteningTest_RecvHostTransfer
xla/tools/hlo_control_flow_flattening_test.cc
HloInstruction* CreateConstant(const Shape& shape, HloComputation* computation) { if (shape.IsTuple()) { std::vector<HloInstruction*> tuple_arguments(shape.tuple_shapes_size()); for (int index = 0; index < shape.tuple_shapes_size(); ++index) { tuple_arguments[index] = CreateConstant(shape.tuple_shapes(index), computation); } return computation->AddInstruction( HloInstruction::CreateTuple(tuple_arguments)); } else { return computation->AddInstruction( HloInstruction::CreateConstant(Literal::CreateFromShape(shape))); } } void PrintSubexpression(HloInstruction* inst, int depth) { if (depth == 0) { return; } for (auto* operand : inst->operands()) { PrintSubexpression(operand, depth - 1); } VLOG(2) << inst->ToString(); } VLOG(2) << inst->ToString(); bool IsConstantScalarInt(const HloInstruction* inst) { return inst->opcode() == HloOpcode::kConstant && ShapeUtil::IsEffectiveScalar(inst->shape()) && inst->shape().IsInteger(); } bool IsNotContainedInLoop(const HloInstruction& while_hlo, const CallGraph& call_graph) { const HloComputation* computation = while_hlo.parent(); while (!computation->IsEntryComputation()) { auto& node = call_graph.GetNode(computation); CHECK_EQ(node.caller_callsites().size(), 1) << "The module is not flattened!"; auto& callsite = node.caller_callsites()[0]; if (callsite.instruction()->opcode() == HloOpcode::kWhile) { // Another while loop has been found traversing up the call tree. return false; } computation = callsite.instruction()->parent(); } // No calling while loops were found. return true; } int GetLoopBound(const HloInstruction& while_hlo, const int default_loop_count, const int max_loop_count) { HloInstruction* condition = while_hlo.while_condition()->root_instruction(); if (condition->opcode() == HloOpcode::kCompare) { int64_t value = 0; Comparison::Direction cmp = condition->comparison_direction(); if ((cmp == Comparison::Direction::kLt || cmp == Comparison::Direction::kLe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(1))) { value = *condition->operand(1)->literal().GetFirstInteger(); } else if ((cmp == Comparison::Direction::kGt || cmp == Comparison::Direction::kGe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(0))) { value = *condition->operand(0)->literal().GetFirstInteger(); } if (value > 0) { // Caps to a max loop count to avoid long execution times. return std::min(value, static_cast<int64_t>(max_loop_count)); } } return default_loop_count; } int GetLoopBoundWithOuterLoopMax(const HloInstruction& while_hlo, const CallGraph& call_graph, const int default_loop_count, const int max_outer_loop_count, const int max_loop_count) { int loop_bound = GetLoopBound(while_hlo, default_loop_count, max_loop_count); if (loop_bound > max_outer_loop_count) { // First does the inexpensive loop bound check to avoid as many // expensive graph traversals in IsNotContainedInLoop as possible. if (IsNotContainedInLoop(while_hlo, call_graph)) { return max_outer_loop_count; } } return loop_bound; } absl::Status HloControlFlowFlattening::FlattenWhileLoop( HloInstruction* while_hlo, const CallGraph& call_graph) const { CHECK_EQ(while_hlo->opcode(), HloOpcode::kWhile); HloComputation* computation = while_hlo->parent(); // Add a new induction variable. HloInstruction* initialization = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(0))); // Create a new while operand with the induction variable added. HloInstruction* old_tuple = while_hlo->mutable_operand(0); HloInstruction* new_tuple = TupleUtil::AppendSuffix(old_tuple, {initialization}); int new_tuple_size = new_tuple->shape().tuple_shapes().size(); TF_RETURN_IF_ERROR(while_hlo->ReplaceOperandWithDifferentShape(0, new_tuple)); auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; // Replace the given tuple-shaped instruction of size N in each of its // non-get-tuple-element users with a new tuple instruction which has the // first N - 1 elements. auto replace_non_gte_users = [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; { // Add the new variable to the while loop condition. HloComputation* condition = while_hlo->while_condition(); TF_RETURN_IF_ERROR(change_op_shape(condition->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(condition->parameter_instruction(0)).status()); if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); PrintSubexpression(condition->root_instruction(), /*depth=*/3); } const int loop_bound = GetLoopBoundWithOuterLoopMax( *while_hlo, call_graph, while_execution_count_, max_outer_loop_count_, max_loop_count_); VLOG(1) << "loop_bound = " << loop_bound; HloInstruction* limit = condition->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(loop_bound))); Shape shape = initialization->shape(); HloInstruction* induction_variable = condition->AddInstruction(HloInstruction::CreateGetTupleElement( shape, condition->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* compare = condition->AddInstruction(HloInstruction::CreateCompare( ShapeUtil::MakeShape(PRED, {}), induction_variable, limit, ComparisonDirection::kLt)); TF_RETURN_IF_ERROR( condition->ReplaceInstruction(condition->root_instruction(), compare)); } { // Add the new variable to the while loop body. HloComputation* body = while_hlo->while_body(); TF_RETURN_IF_ERROR(change_op_shape(body->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(body->parameter_instruction(0)).status()); HloInstruction* old_root = body->root_instruction(); Shape shape = initialization->shape(); HloInstruction* induction_variable = body->AddInstruction(HloInstruction::CreateGetTupleElement( shape, body->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* increment = body->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(1))); induction_variable = body->AddInstruction(HloInstruction::CreateBinary( shape, HloOpcode::kAdd, induction_variable, increment)); HloInstruction* new_root = TupleUtil::AppendSuffix(old_root, {induction_variable}); body->set_root_instruction(new_root, /*accept_different_shape=*/true); } // Snapshot the users of while hlo before we add new users. std::vector<HloInstruction*> while_users(while_hlo->users().begin(), while_hlo->users().end()); // Take care of the users of this while loop. TF_RETURN_IF_ERROR(change_op_shape(while_hlo)); TF_ASSIGN_OR_RETURN(HloInstruction * prefix, replace_non_gte_users(while_hlo)); // If the while loop had been the root of its computation, make the prefix new // root. if (while_hlo->parent()->root_instruction() == while_hlo) { // We need to set accept_different_shape=true to reset the root shape to the // original, because we have already changed the shape of the old root // (while). if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix(while_hlo, new_tuple_size - 1); } while_hlo->parent()->set_root_instruction(prefix, /*accept_different_shape=*/true); } return absl::OkStatus(); } auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); VLOG(1) << "loop_bound = " << loop_bound; absl::Status HloControlFlowFlattening::RemoveInfeed( HloInstruction* infeed_hlo) const { CHECK_EQ(infeed_hlo->opcode(), HloOpcode::kInfeed); HloComputation* computation = infeed_hlo->parent(); CHECK_EQ(infeed_hlo->shape().tuple_shapes_size(), 2); const Shape& infeed_shape = ShapeUtil::GetSubshape(infeed_hlo->shape(), {0}); HloInstruction* custom_call = computation->AddInstruction( HloInstruction::CreateCustomCall(infeed_shape, {}, kNopCustomCallTarget)); // Create a new tuple consisting of the constant and the token that was // originally the operand of infeed, and replace the infeed operation. auto new_tuple = HloInstruction::CreateTuple( {custom_call, infeed_hlo->mutable_operand(0)}); TF_RETURN_IF_ERROR( computation->ReplaceWithNewInstruction(infeed_hlo, std::move(new_tuple))); custom_call->SetAndSanitizeName(infeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveRecvAndRecvDone( HloInstruction* recv_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(recv_done->opcode(), HloOpcode::kRecvDone); CHECK_EQ(recv_done->operand_count(), 1); HloInstruction* recv = recv_done->mutable_operand(0); CHECK_EQ(recv->opcode(), HloOpcode::kRecv); HloComputation* computation = recv_done->parent(); CHECK_EQ(recv_done->shape().tuple_shapes_size(), 2); HloModule* module = computation->parent(); HloInstruction* custom_call_recv = computation->AddInstruction(HloInstruction::CreateCustomCall( recv->shape(), recv->operands(), kNopCustomCallTarget)); std::string original_recv_name(recv->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv, custom_call_recv); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(recv, custom_call_recv)); custom_call_recv->SetAndSanitizeName(original_recv_name); std::string original_recv_done_name(recv_done->name()); HloInstruction* custom_call_recv_done = computation->AddInstruction( HloInstruction::CreateCustomCall( recv_done->shape(), recv_done->operands(), kNopCustomCallTarget), recv_done->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv_done, custom_call_recv_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(recv_done, custom_call_recv_done)); custom_call_recv_done->SetAndSanitizeName(original_recv_done_name); return std::make_pair(custom_call_recv, custom_call_recv_done); } absl::Status HloControlFlowFlattening::RemoveOutfeed( HloInstruction* outfeed_hlo) const { CHECK_EQ(outfeed_hlo->opcode(), HloOpcode::kOutfeed); HloComputation* computation = outfeed_hlo->parent(); // Replace the outfeed with a no-op custom call with side effect to ensure the // operands aren't DCE'd. HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( outfeed_hlo->shape(), outfeed_hlo->operands(), kNopReturnTokenCustomCallTarget)); Cast<HloCustomCallInstruction>(custom_call) ->set_custom_call_has_side_effect(true); // For SPMD graphs, partitioner requires that side-effecting custom calls have // a sharding that is non-replicated. custom_call->set_sharding(HloSharding::Manual()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(outfeed_hlo, custom_call)); custom_call->SetAndSanitizeName(outfeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveSendAndSendDone( HloInstruction* send_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(send_done->opcode(), HloOpcode::kSendDone); CHECK_EQ(send_done->operand_count(), 1); HloInstruction* send = send_done->mutable_operand(0); CHECK_EQ(send->opcode(), HloOpcode::kSend); HloComputation* computation = send_done->parent(); HloModule* module = computation->parent(); HloInstruction* custom_call_send = computation->AddInstruction(HloInstruction::CreateCustomCall( send->shape(), send->operands(), kNopCustomCallTarget)); std::string original_send_name(send->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send, custom_call_send); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(send, custom_call_send)); custom_call_send->SetAndSanitizeName(original_send_name); HloInstruction* custom_call_send_done = computation->AddInstruction(HloInstruction::CreateCustomCall( send_done->shape(), send_done->operands(), kNopReturnTokenCustomCallTarget)); std::string original_send_done_name(send_done->name()); Cast<HloCustomCallInstruction>(custom_call_send_done) ->set_custom_call_has_side_effect(true); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send_done, custom_call_send_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(send_done, custom_call_send_done)); custom_call_send_done->SetAndSanitizeName(original_send_done_name); return std::make_pair(custom_call_send, custom_call_send_done); } absl::StatusOr<HloInstruction*> HloControlFlowFlattening::RemoveCollective( HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( hlo->shape(), hlo->operands(), kNopCustomCallTarget)); // Copy backend config. This is necessary for a collective op in megacore // fusion. custom_call->CopyBackendConfigFrom(hlo); HloModule* module = computation->parent(); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, hlo, custom_call); } std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, custom_call)); custom_call->SetAndSanitizeName(original_op_name); return custom_call; } absl::Status HloControlFlowFlattening::RemoveId(HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* zero = CreateConstant(hlo->shape(), computation); std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, zero)); zero->SetAndSanitizeName(original_op_name); return absl::OkStatus(); } absl::StatusOr<bool> HloControlFlowFlattening::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { auto call_graph = CallGraph::Build(module); bool changed = false; absl::flat_hash_set<HloInstruction*> removed; for (HloComputation* computation : module->computations(execution_threads)) { // Do not change computations that are wrapped by async calls. Instead we // remove the async callers if needed. if (computation->IsAsyncComputation()) { continue; } for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (removed.contains(instruction)) { // Skip the instruction if it is already removed. continue; } if (flatten_while_loop_ && instruction->opcode() == HloOpcode::kWhile) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(FlattenWhileLoop(instruction, *call_graph)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kInfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveInfeed(instruction)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kOutfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveOutfeed(instruction)); changed = true; } else if (instruction->opcode() == HloOpcode::kSendDone) { auto send_done_instruction = DynCast<HloSendDoneInstruction>(instruction); CHECK(send_done_instruction); if (remove_comm_ || (remove_host_transfer_ && send_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveSendAndSendDone(instruction, &removed).status()); changed = true; } } else if (instruction->opcode() == HloOpcode::kRecvDone) { auto recv_done_instruction = DynCast<HloRecvDoneInstruction>(instruction); CHECK(recv_done_instruction); if (remove_comm_ || (remove_host_transfer_ && recv_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveRecvAndRecvDone(instruction, &removed).status()); changed = true; } } else if (remove_comm_ && IsCollective(instruction) && !instruction->parent()->IsFusionComputation() && (instruction->opcode() != HloOpcode::kAsyncStart && instruction->opcode() != HloOpcode::kAsyncUpdate)) { // We do not remove kAsyncStart or kAsyncUpdate here since we expect // them to be removed as a part of the async chain above. // We should remove the async chain all together because the async // wrapped computation is only associated with the AsyncStart. So we // need to refer to the AsyncStart in order to determine whether // the Done or the Update wraps a collective. if (instruction->opcode() == HloOpcode::kAsyncDone) { while (instruction->opcode() == HloOpcode::kAsyncDone || instruction->opcode() == HloOpcode::kAsyncUpdate || instruction->opcode() == HloOpcode::kAsyncStart) { HloInstruction* operand = instruction->mutable_operand(0); VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); instruction = operand; } } else { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); } changed = true; } else if (remove_comm_ && (instruction->opcode() == HloOpcode::kPartitionId || instruction->opcode() == HloOpcode::kReplicaId || (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == "SliceId"))) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveId(instruction)); changed = true; } } } HloDCE hlo_dce; TF_ASSIGN_OR_RETURN(bool dce_changed, hlo_dce.Run(module, execution_threads)); changed |= dce_changed; // Fix the schedule if the module was scheduled. if (changed && module->has_schedule()) { TF_RETURN_IF_ERROR(module->schedule().Update()); } XLA_VLOG_LINES(3, module->ToString()); return changed; } VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); XLA_VLOG_LINES(3, module->ToString());
#include "xla/tools/hlo_control_flow_flattening.h" #include <memory> #include <utility> #include "absl/strings/str_replace.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/collective_ops_utils.h" #include "xla/service/despecializer.h" #include "xla/service/hlo_verifier.h" #include "xla/service/spmd/spmd_partitioner.h" #include "xla/tests/hlo_test_base.h" #include "tsl/lib/core/status_test_util.h" class HloControlFlowFlatteningTest : public HloTestBase { public: absl::StatusOr<std::unique_ptr<HloModule>> PartitionComputation( std::unique_ptr<VerifiedHloModule> hlo_module, int64_t num_devices = 2) { spmd::SpmdPartitionerOptions options; auto collective_ops_creator = spmd::GetDefaultCollectiveOpsCreator(num_devices, /*num_replicas=*/1); collective_ops_creator.create_cross_partition_all_gather = nullptr; HloModuleConfig config = GetModuleConfigForTest(); config.set_use_spmd_partitioning(true); config.set_num_partitions(num_devices); HloPassPipeline pass("spmd-partitioning"); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); pass.AddPass<spmd::SpmdPartitioner>(num_devices, /*num_replicas=*/1, options, collective_ops_creator); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); TF_RETURN_IF_ERROR(pass.Run(hlo_module.get()).status()); return absl::StatusOr<std::unique_ptr<HloModule>>(std::move(hlo_module)); } }; TEST_F(HloControlFlowFlatteningTest, RecvHostTransfer) { absl::string_view hlo_string = R"( HloModule Recv ENTRY %Recv () -> (f32[], token[]) { %token0 = token[] after-all() %recv = (f32[], u32[], token[]) recv(token[] %token0), channel_id=15, is_host_transfer=true ROOT %recv-done = (f32[], token[]) recv-done((f32[], u32[], token[]) %recv), channel_id=15, is_host_transfer=true %constant = f32[] constant(2.1) %send = (f32[], u32[], token[]) send(f32[] %constant, token[] %token0), channel_id=16, control-predecessors={%recv} %send-done = token[] send-done((f32[], u32[], token[]) %send), channel_id=16 } )"; TF_ASSERT_OK_AND_ASSIGN(auto module, ParseAndReturnVerifiedModule(hlo_string)); ControlDepRemover control_remover; HloControlFlowFlattening flattening(HloControlFlowFlattening::Options{ /*while_execution_count=*/3, /*max_outer_loop_count=*/3, /*max_loop_count=*/3, /*remove_infeed_outfeed=*/true, /*flatten_while_loop=*/true, /*remove_comm=*/false, /*remove_host_transfer=*/true}); TF_ASSERT_OK(control_remover.Run(module.get()).status()); EXPECT_TRUE(flattening.Run(module.get()).value()); TF_ASSERT_OK(HloVerifier(/*layout_sensitive=*/true, /*allow_mixed_precision=*/true) .Run(module.get()) .status()); EXPECT_THAT(module->entry_computation()->root_instruction(), op::CustomCall(op::CustomCall())); EXPECT_EQ(module->entry_computation()->root_instruction()->name(), "recv-done"); EXPECT_EQ(module->entry_computation()->root_instruction()->operand(0)->name(), "recv"); }
HloControlFlowFlatteningTest_ReplicaIdSucceedsWithChange
xla/tools/hlo_control_flow_flattening_test.cc
HloInstruction* CreateConstant(const Shape& shape, HloComputation* computation) { if (shape.IsTuple()) { std::vector<HloInstruction*> tuple_arguments(shape.tuple_shapes_size()); for (int index = 0; index < shape.tuple_shapes_size(); ++index) { tuple_arguments[index] = CreateConstant(shape.tuple_shapes(index), computation); } return computation->AddInstruction( HloInstruction::CreateTuple(tuple_arguments)); } else { return computation->AddInstruction( HloInstruction::CreateConstant(Literal::CreateFromShape(shape))); } } void PrintSubexpression(HloInstruction* inst, int depth) { if (depth == 0) { return; } for (auto* operand : inst->operands()) { PrintSubexpression(operand, depth - 1); } VLOG(2) << inst->ToString(); } VLOG(2) << inst->ToString(); bool IsConstantScalarInt(const HloInstruction* inst) { return inst->opcode() == HloOpcode::kConstant && ShapeUtil::IsEffectiveScalar(inst->shape()) && inst->shape().IsInteger(); } bool IsNotContainedInLoop(const HloInstruction& while_hlo, const CallGraph& call_graph) { const HloComputation* computation = while_hlo.parent(); while (!computation->IsEntryComputation()) { auto& node = call_graph.GetNode(computation); CHECK_EQ(node.caller_callsites().size(), 1) << "The module is not flattened!"; auto& callsite = node.caller_callsites()[0]; if (callsite.instruction()->opcode() == HloOpcode::kWhile) { // Another while loop has been found traversing up the call tree. return false; } computation = callsite.instruction()->parent(); } // No calling while loops were found. return true; } int GetLoopBound(const HloInstruction& while_hlo, const int default_loop_count, const int max_loop_count) { HloInstruction* condition = while_hlo.while_condition()->root_instruction(); if (condition->opcode() == HloOpcode::kCompare) { int64_t value = 0; Comparison::Direction cmp = condition->comparison_direction(); if ((cmp == Comparison::Direction::kLt || cmp == Comparison::Direction::kLe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(1))) { value = *condition->operand(1)->literal().GetFirstInteger(); } else if ((cmp == Comparison::Direction::kGt || cmp == Comparison::Direction::kGe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(0))) { value = *condition->operand(0)->literal().GetFirstInteger(); } if (value > 0) { // Caps to a max loop count to avoid long execution times. return std::min(value, static_cast<int64_t>(max_loop_count)); } } return default_loop_count; } int GetLoopBoundWithOuterLoopMax(const HloInstruction& while_hlo, const CallGraph& call_graph, const int default_loop_count, const int max_outer_loop_count, const int max_loop_count) { int loop_bound = GetLoopBound(while_hlo, default_loop_count, max_loop_count); if (loop_bound > max_outer_loop_count) { // First does the inexpensive loop bound check to avoid as many // expensive graph traversals in IsNotContainedInLoop as possible. if (IsNotContainedInLoop(while_hlo, call_graph)) { return max_outer_loop_count; } } return loop_bound; } absl::Status HloControlFlowFlattening::FlattenWhileLoop( HloInstruction* while_hlo, const CallGraph& call_graph) const { CHECK_EQ(while_hlo->opcode(), HloOpcode::kWhile); HloComputation* computation = while_hlo->parent(); // Add a new induction variable. HloInstruction* initialization = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(0))); // Create a new while operand with the induction variable added. HloInstruction* old_tuple = while_hlo->mutable_operand(0); HloInstruction* new_tuple = TupleUtil::AppendSuffix(old_tuple, {initialization}); int new_tuple_size = new_tuple->shape().tuple_shapes().size(); TF_RETURN_IF_ERROR(while_hlo->ReplaceOperandWithDifferentShape(0, new_tuple)); auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; // Replace the given tuple-shaped instruction of size N in each of its // non-get-tuple-element users with a new tuple instruction which has the // first N - 1 elements. auto replace_non_gte_users = [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; { // Add the new variable to the while loop condition. HloComputation* condition = while_hlo->while_condition(); TF_RETURN_IF_ERROR(change_op_shape(condition->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(condition->parameter_instruction(0)).status()); if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); PrintSubexpression(condition->root_instruction(), /*depth=*/3); } const int loop_bound = GetLoopBoundWithOuterLoopMax( *while_hlo, call_graph, while_execution_count_, max_outer_loop_count_, max_loop_count_); VLOG(1) << "loop_bound = " << loop_bound; HloInstruction* limit = condition->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(loop_bound))); Shape shape = initialization->shape(); HloInstruction* induction_variable = condition->AddInstruction(HloInstruction::CreateGetTupleElement( shape, condition->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* compare = condition->AddInstruction(HloInstruction::CreateCompare( ShapeUtil::MakeShape(PRED, {}), induction_variable, limit, ComparisonDirection::kLt)); TF_RETURN_IF_ERROR( condition->ReplaceInstruction(condition->root_instruction(), compare)); } { // Add the new variable to the while loop body. HloComputation* body = while_hlo->while_body(); TF_RETURN_IF_ERROR(change_op_shape(body->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(body->parameter_instruction(0)).status()); HloInstruction* old_root = body->root_instruction(); Shape shape = initialization->shape(); HloInstruction* induction_variable = body->AddInstruction(HloInstruction::CreateGetTupleElement( shape, body->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* increment = body->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(1))); induction_variable = body->AddInstruction(HloInstruction::CreateBinary( shape, HloOpcode::kAdd, induction_variable, increment)); HloInstruction* new_root = TupleUtil::AppendSuffix(old_root, {induction_variable}); body->set_root_instruction(new_root, /*accept_different_shape=*/true); } // Snapshot the users of while hlo before we add new users. std::vector<HloInstruction*> while_users(while_hlo->users().begin(), while_hlo->users().end()); // Take care of the users of this while loop. TF_RETURN_IF_ERROR(change_op_shape(while_hlo)); TF_ASSIGN_OR_RETURN(HloInstruction * prefix, replace_non_gte_users(while_hlo)); // If the while loop had been the root of its computation, make the prefix new // root. if (while_hlo->parent()->root_instruction() == while_hlo) { // We need to set accept_different_shape=true to reset the root shape to the // original, because we have already changed the shape of the old root // (while). if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix(while_hlo, new_tuple_size - 1); } while_hlo->parent()->set_root_instruction(prefix, /*accept_different_shape=*/true); } return absl::OkStatus(); } auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); VLOG(1) << "loop_bound = " << loop_bound; absl::Status HloControlFlowFlattening::RemoveInfeed( HloInstruction* infeed_hlo) const { CHECK_EQ(infeed_hlo->opcode(), HloOpcode::kInfeed); HloComputation* computation = infeed_hlo->parent(); CHECK_EQ(infeed_hlo->shape().tuple_shapes_size(), 2); const Shape& infeed_shape = ShapeUtil::GetSubshape(infeed_hlo->shape(), {0}); HloInstruction* custom_call = computation->AddInstruction( HloInstruction::CreateCustomCall(infeed_shape, {}, kNopCustomCallTarget)); // Create a new tuple consisting of the constant and the token that was // originally the operand of infeed, and replace the infeed operation. auto new_tuple = HloInstruction::CreateTuple( {custom_call, infeed_hlo->mutable_operand(0)}); TF_RETURN_IF_ERROR( computation->ReplaceWithNewInstruction(infeed_hlo, std::move(new_tuple))); custom_call->SetAndSanitizeName(infeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveRecvAndRecvDone( HloInstruction* recv_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(recv_done->opcode(), HloOpcode::kRecvDone); CHECK_EQ(recv_done->operand_count(), 1); HloInstruction* recv = recv_done->mutable_operand(0); CHECK_EQ(recv->opcode(), HloOpcode::kRecv); HloComputation* computation = recv_done->parent(); CHECK_EQ(recv_done->shape().tuple_shapes_size(), 2); HloModule* module = computation->parent(); HloInstruction* custom_call_recv = computation->AddInstruction(HloInstruction::CreateCustomCall( recv->shape(), recv->operands(), kNopCustomCallTarget)); std::string original_recv_name(recv->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv, custom_call_recv); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(recv, custom_call_recv)); custom_call_recv->SetAndSanitizeName(original_recv_name); std::string original_recv_done_name(recv_done->name()); HloInstruction* custom_call_recv_done = computation->AddInstruction( HloInstruction::CreateCustomCall( recv_done->shape(), recv_done->operands(), kNopCustomCallTarget), recv_done->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv_done, custom_call_recv_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(recv_done, custom_call_recv_done)); custom_call_recv_done->SetAndSanitizeName(original_recv_done_name); return std::make_pair(custom_call_recv, custom_call_recv_done); } absl::Status HloControlFlowFlattening::RemoveOutfeed( HloInstruction* outfeed_hlo) const { CHECK_EQ(outfeed_hlo->opcode(), HloOpcode::kOutfeed); HloComputation* computation = outfeed_hlo->parent(); // Replace the outfeed with a no-op custom call with side effect to ensure the // operands aren't DCE'd. HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( outfeed_hlo->shape(), outfeed_hlo->operands(), kNopReturnTokenCustomCallTarget)); Cast<HloCustomCallInstruction>(custom_call) ->set_custom_call_has_side_effect(true); // For SPMD graphs, partitioner requires that side-effecting custom calls have // a sharding that is non-replicated. custom_call->set_sharding(HloSharding::Manual()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(outfeed_hlo, custom_call)); custom_call->SetAndSanitizeName(outfeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveSendAndSendDone( HloInstruction* send_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(send_done->opcode(), HloOpcode::kSendDone); CHECK_EQ(send_done->operand_count(), 1); HloInstruction* send = send_done->mutable_operand(0); CHECK_EQ(send->opcode(), HloOpcode::kSend); HloComputation* computation = send_done->parent(); HloModule* module = computation->parent(); HloInstruction* custom_call_send = computation->AddInstruction(HloInstruction::CreateCustomCall( send->shape(), send->operands(), kNopCustomCallTarget)); std::string original_send_name(send->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send, custom_call_send); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(send, custom_call_send)); custom_call_send->SetAndSanitizeName(original_send_name); HloInstruction* custom_call_send_done = computation->AddInstruction(HloInstruction::CreateCustomCall( send_done->shape(), send_done->operands(), kNopReturnTokenCustomCallTarget)); std::string original_send_done_name(send_done->name()); Cast<HloCustomCallInstruction>(custom_call_send_done) ->set_custom_call_has_side_effect(true); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send_done, custom_call_send_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(send_done, custom_call_send_done)); custom_call_send_done->SetAndSanitizeName(original_send_done_name); return std::make_pair(custom_call_send, custom_call_send_done); } absl::StatusOr<HloInstruction*> HloControlFlowFlattening::RemoveCollective( HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( hlo->shape(), hlo->operands(), kNopCustomCallTarget)); // Copy backend config. This is necessary for a collective op in megacore // fusion. custom_call->CopyBackendConfigFrom(hlo); HloModule* module = computation->parent(); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, hlo, custom_call); } std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, custom_call)); custom_call->SetAndSanitizeName(original_op_name); return custom_call; } absl::Status HloControlFlowFlattening::RemoveId(HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* zero = CreateConstant(hlo->shape(), computation); std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, zero)); zero->SetAndSanitizeName(original_op_name); return absl::OkStatus(); } absl::StatusOr<bool> HloControlFlowFlattening::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { auto call_graph = CallGraph::Build(module); bool changed = false; absl::flat_hash_set<HloInstruction*> removed; for (HloComputation* computation : module->computations(execution_threads)) { // Do not change computations that are wrapped by async calls. Instead we // remove the async callers if needed. if (computation->IsAsyncComputation()) { continue; } for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (removed.contains(instruction)) { // Skip the instruction if it is already removed. continue; } if (flatten_while_loop_ && instruction->opcode() == HloOpcode::kWhile) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(FlattenWhileLoop(instruction, *call_graph)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kInfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveInfeed(instruction)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kOutfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveOutfeed(instruction)); changed = true; } else if (instruction->opcode() == HloOpcode::kSendDone) { auto send_done_instruction = DynCast<HloSendDoneInstruction>(instruction); CHECK(send_done_instruction); if (remove_comm_ || (remove_host_transfer_ && send_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveSendAndSendDone(instruction, &removed).status()); changed = true; } } else if (instruction->opcode() == HloOpcode::kRecvDone) { auto recv_done_instruction = DynCast<HloRecvDoneInstruction>(instruction); CHECK(recv_done_instruction); if (remove_comm_ || (remove_host_transfer_ && recv_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveRecvAndRecvDone(instruction, &removed).status()); changed = true; } } else if (remove_comm_ && IsCollective(instruction) && !instruction->parent()->IsFusionComputation() && (instruction->opcode() != HloOpcode::kAsyncStart && instruction->opcode() != HloOpcode::kAsyncUpdate)) { // We do not remove kAsyncStart or kAsyncUpdate here since we expect // them to be removed as a part of the async chain above. // We should remove the async chain all together because the async // wrapped computation is only associated with the AsyncStart. So we // need to refer to the AsyncStart in order to determine whether // the Done or the Update wraps a collective. if (instruction->opcode() == HloOpcode::kAsyncDone) { while (instruction->opcode() == HloOpcode::kAsyncDone || instruction->opcode() == HloOpcode::kAsyncUpdate || instruction->opcode() == HloOpcode::kAsyncStart) { HloInstruction* operand = instruction->mutable_operand(0); VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); instruction = operand; } } else { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); } changed = true; } else if (remove_comm_ && (instruction->opcode() == HloOpcode::kPartitionId || instruction->opcode() == HloOpcode::kReplicaId || (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == "SliceId"))) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveId(instruction)); changed = true; } } } HloDCE hlo_dce; TF_ASSIGN_OR_RETURN(bool dce_changed, hlo_dce.Run(module, execution_threads)); changed |= dce_changed; // Fix the schedule if the module was scheduled. if (changed && module->has_schedule()) { TF_RETURN_IF_ERROR(module->schedule().Update()); } XLA_VLOG_LINES(3, module->ToString()); return changed; } VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); XLA_VLOG_LINES(3, module->ToString());
#include "xla/tools/hlo_control_flow_flattening.h" #include <memory> #include <utility> #include "absl/strings/str_replace.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/collective_ops_utils.h" #include "xla/service/despecializer.h" #include "xla/service/hlo_verifier.h" #include "xla/service/spmd/spmd_partitioner.h" #include "xla/tests/hlo_test_base.h" #include "tsl/lib/core/status_test_util.h" class HloControlFlowFlatteningTest : public HloTestBase { public: absl::StatusOr<std::unique_ptr<HloModule>> PartitionComputation( std::unique_ptr<VerifiedHloModule> hlo_module, int64_t num_devices = 2) { spmd::SpmdPartitionerOptions options; auto collective_ops_creator = spmd::GetDefaultCollectiveOpsCreator(num_devices, /*num_replicas=*/1); collective_ops_creator.create_cross_partition_all_gather = nullptr; HloModuleConfig config = GetModuleConfigForTest(); config.set_use_spmd_partitioning(true); config.set_num_partitions(num_devices); HloPassPipeline pass("spmd-partitioning"); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); pass.AddPass<spmd::SpmdPartitioner>(num_devices, /*num_replicas=*/1, options, collective_ops_creator); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); TF_RETURN_IF_ERROR(pass.Run(hlo_module.get()).status()); return absl::StatusOr<std::unique_ptr<HloModule>>(std::move(hlo_module)); } }; TEST_F(HloControlFlowFlatteningTest, ReplicaIdSucceedsWithChange) { absl::string_view hlo_string = R"( HloModule ReplicaId ENTRY ReplicaId { ROOT replica-id.18600 = u32[]{:T(128)} replica-id() } )"; TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<VerifiedHloModule> module, ParseAndReturnVerifiedModule(hlo_string)); HloControlFlowFlattening flattening(HloControlFlowFlattening::Options{}); EXPECT_TRUE(flattening.Run(module.get()).value()); TF_ASSERT_OK(HloVerifier(/*layout_sensitive=*/true, /*allow_mixed_precision=*/true) .Run(module.get()) .status()); EXPECT_THAT(module->entry_computation()->root_instruction(), op::Constant()); EXPECT_EQ(module->entry_computation()->root_instruction()->name(), "replica-id.18600"); }
HloControlFlowFlatteningTest_Send
xla/tools/hlo_control_flow_flattening_test.cc
HloInstruction* CreateConstant(const Shape& shape, HloComputation* computation) { if (shape.IsTuple()) { std::vector<HloInstruction*> tuple_arguments(shape.tuple_shapes_size()); for (int index = 0; index < shape.tuple_shapes_size(); ++index) { tuple_arguments[index] = CreateConstant(shape.tuple_shapes(index), computation); } return computation->AddInstruction( HloInstruction::CreateTuple(tuple_arguments)); } else { return computation->AddInstruction( HloInstruction::CreateConstant(Literal::CreateFromShape(shape))); } } void PrintSubexpression(HloInstruction* inst, int depth) { if (depth == 0) { return; } for (auto* operand : inst->operands()) { PrintSubexpression(operand, depth - 1); } VLOG(2) << inst->ToString(); } VLOG(2) << inst->ToString(); bool IsConstantScalarInt(const HloInstruction* inst) { return inst->opcode() == HloOpcode::kConstant && ShapeUtil::IsEffectiveScalar(inst->shape()) && inst->shape().IsInteger(); } bool IsNotContainedInLoop(const HloInstruction& while_hlo, const CallGraph& call_graph) { const HloComputation* computation = while_hlo.parent(); while (!computation->IsEntryComputation()) { auto& node = call_graph.GetNode(computation); CHECK_EQ(node.caller_callsites().size(), 1) << "The module is not flattened!"; auto& callsite = node.caller_callsites()[0]; if (callsite.instruction()->opcode() == HloOpcode::kWhile) { // Another while loop has been found traversing up the call tree. return false; } computation = callsite.instruction()->parent(); } // No calling while loops were found. return true; } int GetLoopBound(const HloInstruction& while_hlo, const int default_loop_count, const int max_loop_count) { HloInstruction* condition = while_hlo.while_condition()->root_instruction(); if (condition->opcode() == HloOpcode::kCompare) { int64_t value = 0; Comparison::Direction cmp = condition->comparison_direction(); if ((cmp == Comparison::Direction::kLt || cmp == Comparison::Direction::kLe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(1))) { value = *condition->operand(1)->literal().GetFirstInteger(); } else if ((cmp == Comparison::Direction::kGt || cmp == Comparison::Direction::kGe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(0))) { value = *condition->operand(0)->literal().GetFirstInteger(); } if (value > 0) { // Caps to a max loop count to avoid long execution times. return std::min(value, static_cast<int64_t>(max_loop_count)); } } return default_loop_count; } int GetLoopBoundWithOuterLoopMax(const HloInstruction& while_hlo, const CallGraph& call_graph, const int default_loop_count, const int max_outer_loop_count, const int max_loop_count) { int loop_bound = GetLoopBound(while_hlo, default_loop_count, max_loop_count); if (loop_bound > max_outer_loop_count) { // First does the inexpensive loop bound check to avoid as many // expensive graph traversals in IsNotContainedInLoop as possible. if (IsNotContainedInLoop(while_hlo, call_graph)) { return max_outer_loop_count; } } return loop_bound; } absl::Status HloControlFlowFlattening::FlattenWhileLoop( HloInstruction* while_hlo, const CallGraph& call_graph) const { CHECK_EQ(while_hlo->opcode(), HloOpcode::kWhile); HloComputation* computation = while_hlo->parent(); // Add a new induction variable. HloInstruction* initialization = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(0))); // Create a new while operand with the induction variable added. HloInstruction* old_tuple = while_hlo->mutable_operand(0); HloInstruction* new_tuple = TupleUtil::AppendSuffix(old_tuple, {initialization}); int new_tuple_size = new_tuple->shape().tuple_shapes().size(); TF_RETURN_IF_ERROR(while_hlo->ReplaceOperandWithDifferentShape(0, new_tuple)); auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; // Replace the given tuple-shaped instruction of size N in each of its // non-get-tuple-element users with a new tuple instruction which has the // first N - 1 elements. auto replace_non_gte_users = [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; { // Add the new variable to the while loop condition. HloComputation* condition = while_hlo->while_condition(); TF_RETURN_IF_ERROR(change_op_shape(condition->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(condition->parameter_instruction(0)).status()); if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); PrintSubexpression(condition->root_instruction(), /*depth=*/3); } const int loop_bound = GetLoopBoundWithOuterLoopMax( *while_hlo, call_graph, while_execution_count_, max_outer_loop_count_, max_loop_count_); VLOG(1) << "loop_bound = " << loop_bound; HloInstruction* limit = condition->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(loop_bound))); Shape shape = initialization->shape(); HloInstruction* induction_variable = condition->AddInstruction(HloInstruction::CreateGetTupleElement( shape, condition->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* compare = condition->AddInstruction(HloInstruction::CreateCompare( ShapeUtil::MakeShape(PRED, {}), induction_variable, limit, ComparisonDirection::kLt)); TF_RETURN_IF_ERROR( condition->ReplaceInstruction(condition->root_instruction(), compare)); } { // Add the new variable to the while loop body. HloComputation* body = while_hlo->while_body(); TF_RETURN_IF_ERROR(change_op_shape(body->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(body->parameter_instruction(0)).status()); HloInstruction* old_root = body->root_instruction(); Shape shape = initialization->shape(); HloInstruction* induction_variable = body->AddInstruction(HloInstruction::CreateGetTupleElement( shape, body->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* increment = body->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(1))); induction_variable = body->AddInstruction(HloInstruction::CreateBinary( shape, HloOpcode::kAdd, induction_variable, increment)); HloInstruction* new_root = TupleUtil::AppendSuffix(old_root, {induction_variable}); body->set_root_instruction(new_root, /*accept_different_shape=*/true); } // Snapshot the users of while hlo before we add new users. std::vector<HloInstruction*> while_users(while_hlo->users().begin(), while_hlo->users().end()); // Take care of the users of this while loop. TF_RETURN_IF_ERROR(change_op_shape(while_hlo)); TF_ASSIGN_OR_RETURN(HloInstruction * prefix, replace_non_gte_users(while_hlo)); // If the while loop had been the root of its computation, make the prefix new // root. if (while_hlo->parent()->root_instruction() == while_hlo) { // We need to set accept_different_shape=true to reset the root shape to the // original, because we have already changed the shape of the old root // (while). if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix(while_hlo, new_tuple_size - 1); } while_hlo->parent()->set_root_instruction(prefix, /*accept_different_shape=*/true); } return absl::OkStatus(); } auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); VLOG(1) << "loop_bound = " << loop_bound; absl::Status HloControlFlowFlattening::RemoveInfeed( HloInstruction* infeed_hlo) const { CHECK_EQ(infeed_hlo->opcode(), HloOpcode::kInfeed); HloComputation* computation = infeed_hlo->parent(); CHECK_EQ(infeed_hlo->shape().tuple_shapes_size(), 2); const Shape& infeed_shape = ShapeUtil::GetSubshape(infeed_hlo->shape(), {0}); HloInstruction* custom_call = computation->AddInstruction( HloInstruction::CreateCustomCall(infeed_shape, {}, kNopCustomCallTarget)); // Create a new tuple consisting of the constant and the token that was // originally the operand of infeed, and replace the infeed operation. auto new_tuple = HloInstruction::CreateTuple( {custom_call, infeed_hlo->mutable_operand(0)}); TF_RETURN_IF_ERROR( computation->ReplaceWithNewInstruction(infeed_hlo, std::move(new_tuple))); custom_call->SetAndSanitizeName(infeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveRecvAndRecvDone( HloInstruction* recv_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(recv_done->opcode(), HloOpcode::kRecvDone); CHECK_EQ(recv_done->operand_count(), 1); HloInstruction* recv = recv_done->mutable_operand(0); CHECK_EQ(recv->opcode(), HloOpcode::kRecv); HloComputation* computation = recv_done->parent(); CHECK_EQ(recv_done->shape().tuple_shapes_size(), 2); HloModule* module = computation->parent(); HloInstruction* custom_call_recv = computation->AddInstruction(HloInstruction::CreateCustomCall( recv->shape(), recv->operands(), kNopCustomCallTarget)); std::string original_recv_name(recv->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv, custom_call_recv); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(recv, custom_call_recv)); custom_call_recv->SetAndSanitizeName(original_recv_name); std::string original_recv_done_name(recv_done->name()); HloInstruction* custom_call_recv_done = computation->AddInstruction( HloInstruction::CreateCustomCall( recv_done->shape(), recv_done->operands(), kNopCustomCallTarget), recv_done->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv_done, custom_call_recv_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(recv_done, custom_call_recv_done)); custom_call_recv_done->SetAndSanitizeName(original_recv_done_name); return std::make_pair(custom_call_recv, custom_call_recv_done); } absl::Status HloControlFlowFlattening::RemoveOutfeed( HloInstruction* outfeed_hlo) const { CHECK_EQ(outfeed_hlo->opcode(), HloOpcode::kOutfeed); HloComputation* computation = outfeed_hlo->parent(); // Replace the outfeed with a no-op custom call with side effect to ensure the // operands aren't DCE'd. HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( outfeed_hlo->shape(), outfeed_hlo->operands(), kNopReturnTokenCustomCallTarget)); Cast<HloCustomCallInstruction>(custom_call) ->set_custom_call_has_side_effect(true); // For SPMD graphs, partitioner requires that side-effecting custom calls have // a sharding that is non-replicated. custom_call->set_sharding(HloSharding::Manual()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(outfeed_hlo, custom_call)); custom_call->SetAndSanitizeName(outfeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveSendAndSendDone( HloInstruction* send_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(send_done->opcode(), HloOpcode::kSendDone); CHECK_EQ(send_done->operand_count(), 1); HloInstruction* send = send_done->mutable_operand(0); CHECK_EQ(send->opcode(), HloOpcode::kSend); HloComputation* computation = send_done->parent(); HloModule* module = computation->parent(); HloInstruction* custom_call_send = computation->AddInstruction(HloInstruction::CreateCustomCall( send->shape(), send->operands(), kNopCustomCallTarget)); std::string original_send_name(send->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send, custom_call_send); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(send, custom_call_send)); custom_call_send->SetAndSanitizeName(original_send_name); HloInstruction* custom_call_send_done = computation->AddInstruction(HloInstruction::CreateCustomCall( send_done->shape(), send_done->operands(), kNopReturnTokenCustomCallTarget)); std::string original_send_done_name(send_done->name()); Cast<HloCustomCallInstruction>(custom_call_send_done) ->set_custom_call_has_side_effect(true); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send_done, custom_call_send_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(send_done, custom_call_send_done)); custom_call_send_done->SetAndSanitizeName(original_send_done_name); return std::make_pair(custom_call_send, custom_call_send_done); } absl::StatusOr<HloInstruction*> HloControlFlowFlattening::RemoveCollective( HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( hlo->shape(), hlo->operands(), kNopCustomCallTarget)); // Copy backend config. This is necessary for a collective op in megacore // fusion. custom_call->CopyBackendConfigFrom(hlo); HloModule* module = computation->parent(); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, hlo, custom_call); } std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, custom_call)); custom_call->SetAndSanitizeName(original_op_name); return custom_call; } absl::Status HloControlFlowFlattening::RemoveId(HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* zero = CreateConstant(hlo->shape(), computation); std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, zero)); zero->SetAndSanitizeName(original_op_name); return absl::OkStatus(); } absl::StatusOr<bool> HloControlFlowFlattening::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { auto call_graph = CallGraph::Build(module); bool changed = false; absl::flat_hash_set<HloInstruction*> removed; for (HloComputation* computation : module->computations(execution_threads)) { // Do not change computations that are wrapped by async calls. Instead we // remove the async callers if needed. if (computation->IsAsyncComputation()) { continue; } for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (removed.contains(instruction)) { // Skip the instruction if it is already removed. continue; } if (flatten_while_loop_ && instruction->opcode() == HloOpcode::kWhile) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(FlattenWhileLoop(instruction, *call_graph)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kInfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveInfeed(instruction)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kOutfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveOutfeed(instruction)); changed = true; } else if (instruction->opcode() == HloOpcode::kSendDone) { auto send_done_instruction = DynCast<HloSendDoneInstruction>(instruction); CHECK(send_done_instruction); if (remove_comm_ || (remove_host_transfer_ && send_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveSendAndSendDone(instruction, &removed).status()); changed = true; } } else if (instruction->opcode() == HloOpcode::kRecvDone) { auto recv_done_instruction = DynCast<HloRecvDoneInstruction>(instruction); CHECK(recv_done_instruction); if (remove_comm_ || (remove_host_transfer_ && recv_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveRecvAndRecvDone(instruction, &removed).status()); changed = true; } } else if (remove_comm_ && IsCollective(instruction) && !instruction->parent()->IsFusionComputation() && (instruction->opcode() != HloOpcode::kAsyncStart && instruction->opcode() != HloOpcode::kAsyncUpdate)) { // We do not remove kAsyncStart or kAsyncUpdate here since we expect // them to be removed as a part of the async chain above. // We should remove the async chain all together because the async // wrapped computation is only associated with the AsyncStart. So we // need to refer to the AsyncStart in order to determine whether // the Done or the Update wraps a collective. if (instruction->opcode() == HloOpcode::kAsyncDone) { while (instruction->opcode() == HloOpcode::kAsyncDone || instruction->opcode() == HloOpcode::kAsyncUpdate || instruction->opcode() == HloOpcode::kAsyncStart) { HloInstruction* operand = instruction->mutable_operand(0); VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); instruction = operand; } } else { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); } changed = true; } else if (remove_comm_ && (instruction->opcode() == HloOpcode::kPartitionId || instruction->opcode() == HloOpcode::kReplicaId || (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == "SliceId"))) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveId(instruction)); changed = true; } } } HloDCE hlo_dce; TF_ASSIGN_OR_RETURN(bool dce_changed, hlo_dce.Run(module, execution_threads)); changed |= dce_changed; // Fix the schedule if the module was scheduled. if (changed && module->has_schedule()) { TF_RETURN_IF_ERROR(module->schedule().Update()); } XLA_VLOG_LINES(3, module->ToString()); return changed; } VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); XLA_VLOG_LINES(3, module->ToString());
#include "xla/tools/hlo_control_flow_flattening.h" #include <memory> #include <utility> #include "absl/strings/str_replace.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/collective_ops_utils.h" #include "xla/service/despecializer.h" #include "xla/service/hlo_verifier.h" #include "xla/service/spmd/spmd_partitioner.h" #include "xla/tests/hlo_test_base.h" #include "tsl/lib/core/status_test_util.h" class HloControlFlowFlatteningTest : public HloTestBase { public: absl::StatusOr<std::unique_ptr<HloModule>> PartitionComputation( std::unique_ptr<VerifiedHloModule> hlo_module, int64_t num_devices = 2) { spmd::SpmdPartitionerOptions options; auto collective_ops_creator = spmd::GetDefaultCollectiveOpsCreator(num_devices, /*num_replicas=*/1); collective_ops_creator.create_cross_partition_all_gather = nullptr; HloModuleConfig config = GetModuleConfigForTest(); config.set_use_spmd_partitioning(true); config.set_num_partitions(num_devices); HloPassPipeline pass("spmd-partitioning"); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); pass.AddPass<spmd::SpmdPartitioner>(num_devices, /*num_replicas=*/1, options, collective_ops_creator); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); TF_RETURN_IF_ERROR(pass.Run(hlo_module.get()).status()); return absl::StatusOr<std::unique_ptr<HloModule>>(std::move(hlo_module)); } }; TEST_F(HloControlFlowFlatteningTest, Send) { absl::string_view hlo_string = R"( HloModule Send ENTRY %Send () -> token[] { %token0 = token[] after-all() %recv = (f32[], u32[], token[]) recv(token[] %token0), channel_id=15 %recv-done = (f32[], token[]) recv-done((f32[], u32[], token[]) %recv), channel_id=15 %constant = f32[] constant(2.1) %send = (f32[], u32[], token[]) send(f32[] %constant, token[] %token0), channel_id=16, control-predecessors={%recv} ROOT %send-done = token[] send-done((f32[], u32[], token[]) %send), channel_id=16 } )"; TF_ASSERT_OK_AND_ASSIGN(auto module, ParseAndReturnVerifiedModule(hlo_string)); ControlDepRemover control_remover; HloControlFlowFlattening flattening( HloControlFlowFlattening::Options{/*while_execution_count=*/3}); TF_ASSERT_OK(control_remover.Run(module.get()).status()); EXPECT_TRUE(flattening.Run(module.get()).value()); TF_ASSERT_OK(HloVerifier(/*layout_sensitive=*/true, /*allow_mixed_precision=*/true) .Run(module.get()) .status()); EXPECT_THAT(module->entry_computation()->root_instruction(), op::CustomCall(op::CustomCall())); EXPECT_EQ(module->entry_computation()->root_instruction()->name(), "send-done"); EXPECT_EQ(module->entry_computation()->root_instruction()->operand(0)->name(), "send"); }
HloControlFlowFlatteningTest_SendHostTransfer
xla/tools/hlo_control_flow_flattening_test.cc
HloInstruction* CreateConstant(const Shape& shape, HloComputation* computation) { if (shape.IsTuple()) { std::vector<HloInstruction*> tuple_arguments(shape.tuple_shapes_size()); for (int index = 0; index < shape.tuple_shapes_size(); ++index) { tuple_arguments[index] = CreateConstant(shape.tuple_shapes(index), computation); } return computation->AddInstruction( HloInstruction::CreateTuple(tuple_arguments)); } else { return computation->AddInstruction( HloInstruction::CreateConstant(Literal::CreateFromShape(shape))); } } void PrintSubexpression(HloInstruction* inst, int depth) { if (depth == 0) { return; } for (auto* operand : inst->operands()) { PrintSubexpression(operand, depth - 1); } VLOG(2) << inst->ToString(); } VLOG(2) << inst->ToString(); bool IsConstantScalarInt(const HloInstruction* inst) { return inst->opcode() == HloOpcode::kConstant && ShapeUtil::IsEffectiveScalar(inst->shape()) && inst->shape().IsInteger(); } bool IsNotContainedInLoop(const HloInstruction& while_hlo, const CallGraph& call_graph) { const HloComputation* computation = while_hlo.parent(); while (!computation->IsEntryComputation()) { auto& node = call_graph.GetNode(computation); CHECK_EQ(node.caller_callsites().size(), 1) << "The module is not flattened!"; auto& callsite = node.caller_callsites()[0]; if (callsite.instruction()->opcode() == HloOpcode::kWhile) { // Another while loop has been found traversing up the call tree. return false; } computation = callsite.instruction()->parent(); } // No calling while loops were found. return true; } int GetLoopBound(const HloInstruction& while_hlo, const int default_loop_count, const int max_loop_count) { HloInstruction* condition = while_hlo.while_condition()->root_instruction(); if (condition->opcode() == HloOpcode::kCompare) { int64_t value = 0; Comparison::Direction cmp = condition->comparison_direction(); if ((cmp == Comparison::Direction::kLt || cmp == Comparison::Direction::kLe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(1))) { value = *condition->operand(1)->literal().GetFirstInteger(); } else if ((cmp == Comparison::Direction::kGt || cmp == Comparison::Direction::kGe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(0))) { value = *condition->operand(0)->literal().GetFirstInteger(); } if (value > 0) { // Caps to a max loop count to avoid long execution times. return std::min(value, static_cast<int64_t>(max_loop_count)); } } return default_loop_count; } int GetLoopBoundWithOuterLoopMax(const HloInstruction& while_hlo, const CallGraph& call_graph, const int default_loop_count, const int max_outer_loop_count, const int max_loop_count) { int loop_bound = GetLoopBound(while_hlo, default_loop_count, max_loop_count); if (loop_bound > max_outer_loop_count) { // First does the inexpensive loop bound check to avoid as many // expensive graph traversals in IsNotContainedInLoop as possible. if (IsNotContainedInLoop(while_hlo, call_graph)) { return max_outer_loop_count; } } return loop_bound; } absl::Status HloControlFlowFlattening::FlattenWhileLoop( HloInstruction* while_hlo, const CallGraph& call_graph) const { CHECK_EQ(while_hlo->opcode(), HloOpcode::kWhile); HloComputation* computation = while_hlo->parent(); // Add a new induction variable. HloInstruction* initialization = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(0))); // Create a new while operand with the induction variable added. HloInstruction* old_tuple = while_hlo->mutable_operand(0); HloInstruction* new_tuple = TupleUtil::AppendSuffix(old_tuple, {initialization}); int new_tuple_size = new_tuple->shape().tuple_shapes().size(); TF_RETURN_IF_ERROR(while_hlo->ReplaceOperandWithDifferentShape(0, new_tuple)); auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; // Replace the given tuple-shaped instruction of size N in each of its // non-get-tuple-element users with a new tuple instruction which has the // first N - 1 elements. auto replace_non_gte_users = [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; { // Add the new variable to the while loop condition. HloComputation* condition = while_hlo->while_condition(); TF_RETURN_IF_ERROR(change_op_shape(condition->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(condition->parameter_instruction(0)).status()); if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); PrintSubexpression(condition->root_instruction(), /*depth=*/3); } const int loop_bound = GetLoopBoundWithOuterLoopMax( *while_hlo, call_graph, while_execution_count_, max_outer_loop_count_, max_loop_count_); VLOG(1) << "loop_bound = " << loop_bound; HloInstruction* limit = condition->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(loop_bound))); Shape shape = initialization->shape(); HloInstruction* induction_variable = condition->AddInstruction(HloInstruction::CreateGetTupleElement( shape, condition->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* compare = condition->AddInstruction(HloInstruction::CreateCompare( ShapeUtil::MakeShape(PRED, {}), induction_variable, limit, ComparisonDirection::kLt)); TF_RETURN_IF_ERROR( condition->ReplaceInstruction(condition->root_instruction(), compare)); } { // Add the new variable to the while loop body. HloComputation* body = while_hlo->while_body(); TF_RETURN_IF_ERROR(change_op_shape(body->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(body->parameter_instruction(0)).status()); HloInstruction* old_root = body->root_instruction(); Shape shape = initialization->shape(); HloInstruction* induction_variable = body->AddInstruction(HloInstruction::CreateGetTupleElement( shape, body->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* increment = body->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(1))); induction_variable = body->AddInstruction(HloInstruction::CreateBinary( shape, HloOpcode::kAdd, induction_variable, increment)); HloInstruction* new_root = TupleUtil::AppendSuffix(old_root, {induction_variable}); body->set_root_instruction(new_root, /*accept_different_shape=*/true); } // Snapshot the users of while hlo before we add new users. std::vector<HloInstruction*> while_users(while_hlo->users().begin(), while_hlo->users().end()); // Take care of the users of this while loop. TF_RETURN_IF_ERROR(change_op_shape(while_hlo)); TF_ASSIGN_OR_RETURN(HloInstruction * prefix, replace_non_gte_users(while_hlo)); // If the while loop had been the root of its computation, make the prefix new // root. if (while_hlo->parent()->root_instruction() == while_hlo) { // We need to set accept_different_shape=true to reset the root shape to the // original, because we have already changed the shape of the old root // (while). if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix(while_hlo, new_tuple_size - 1); } while_hlo->parent()->set_root_instruction(prefix, /*accept_different_shape=*/true); } return absl::OkStatus(); } auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); VLOG(1) << "loop_bound = " << loop_bound; absl::Status HloControlFlowFlattening::RemoveInfeed( HloInstruction* infeed_hlo) const { CHECK_EQ(infeed_hlo->opcode(), HloOpcode::kInfeed); HloComputation* computation = infeed_hlo->parent(); CHECK_EQ(infeed_hlo->shape().tuple_shapes_size(), 2); const Shape& infeed_shape = ShapeUtil::GetSubshape(infeed_hlo->shape(), {0}); HloInstruction* custom_call = computation->AddInstruction( HloInstruction::CreateCustomCall(infeed_shape, {}, kNopCustomCallTarget)); // Create a new tuple consisting of the constant and the token that was // originally the operand of infeed, and replace the infeed operation. auto new_tuple = HloInstruction::CreateTuple( {custom_call, infeed_hlo->mutable_operand(0)}); TF_RETURN_IF_ERROR( computation->ReplaceWithNewInstruction(infeed_hlo, std::move(new_tuple))); custom_call->SetAndSanitizeName(infeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveRecvAndRecvDone( HloInstruction* recv_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(recv_done->opcode(), HloOpcode::kRecvDone); CHECK_EQ(recv_done->operand_count(), 1); HloInstruction* recv = recv_done->mutable_operand(0); CHECK_EQ(recv->opcode(), HloOpcode::kRecv); HloComputation* computation = recv_done->parent(); CHECK_EQ(recv_done->shape().tuple_shapes_size(), 2); HloModule* module = computation->parent(); HloInstruction* custom_call_recv = computation->AddInstruction(HloInstruction::CreateCustomCall( recv->shape(), recv->operands(), kNopCustomCallTarget)); std::string original_recv_name(recv->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv, custom_call_recv); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(recv, custom_call_recv)); custom_call_recv->SetAndSanitizeName(original_recv_name); std::string original_recv_done_name(recv_done->name()); HloInstruction* custom_call_recv_done = computation->AddInstruction( HloInstruction::CreateCustomCall( recv_done->shape(), recv_done->operands(), kNopCustomCallTarget), recv_done->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv_done, custom_call_recv_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(recv_done, custom_call_recv_done)); custom_call_recv_done->SetAndSanitizeName(original_recv_done_name); return std::make_pair(custom_call_recv, custom_call_recv_done); } absl::Status HloControlFlowFlattening::RemoveOutfeed( HloInstruction* outfeed_hlo) const { CHECK_EQ(outfeed_hlo->opcode(), HloOpcode::kOutfeed); HloComputation* computation = outfeed_hlo->parent(); // Replace the outfeed with a no-op custom call with side effect to ensure the // operands aren't DCE'd. HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( outfeed_hlo->shape(), outfeed_hlo->operands(), kNopReturnTokenCustomCallTarget)); Cast<HloCustomCallInstruction>(custom_call) ->set_custom_call_has_side_effect(true); // For SPMD graphs, partitioner requires that side-effecting custom calls have // a sharding that is non-replicated. custom_call->set_sharding(HloSharding::Manual()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(outfeed_hlo, custom_call)); custom_call->SetAndSanitizeName(outfeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveSendAndSendDone( HloInstruction* send_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(send_done->opcode(), HloOpcode::kSendDone); CHECK_EQ(send_done->operand_count(), 1); HloInstruction* send = send_done->mutable_operand(0); CHECK_EQ(send->opcode(), HloOpcode::kSend); HloComputation* computation = send_done->parent(); HloModule* module = computation->parent(); HloInstruction* custom_call_send = computation->AddInstruction(HloInstruction::CreateCustomCall( send->shape(), send->operands(), kNopCustomCallTarget)); std::string original_send_name(send->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send, custom_call_send); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(send, custom_call_send)); custom_call_send->SetAndSanitizeName(original_send_name); HloInstruction* custom_call_send_done = computation->AddInstruction(HloInstruction::CreateCustomCall( send_done->shape(), send_done->operands(), kNopReturnTokenCustomCallTarget)); std::string original_send_done_name(send_done->name()); Cast<HloCustomCallInstruction>(custom_call_send_done) ->set_custom_call_has_side_effect(true); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send_done, custom_call_send_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(send_done, custom_call_send_done)); custom_call_send_done->SetAndSanitizeName(original_send_done_name); return std::make_pair(custom_call_send, custom_call_send_done); } absl::StatusOr<HloInstruction*> HloControlFlowFlattening::RemoveCollective( HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( hlo->shape(), hlo->operands(), kNopCustomCallTarget)); // Copy backend config. This is necessary for a collective op in megacore // fusion. custom_call->CopyBackendConfigFrom(hlo); HloModule* module = computation->parent(); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, hlo, custom_call); } std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, custom_call)); custom_call->SetAndSanitizeName(original_op_name); return custom_call; } absl::Status HloControlFlowFlattening::RemoveId(HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* zero = CreateConstant(hlo->shape(), computation); std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, zero)); zero->SetAndSanitizeName(original_op_name); return absl::OkStatus(); } absl::StatusOr<bool> HloControlFlowFlattening::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { auto call_graph = CallGraph::Build(module); bool changed = false; absl::flat_hash_set<HloInstruction*> removed; for (HloComputation* computation : module->computations(execution_threads)) { // Do not change computations that are wrapped by async calls. Instead we // remove the async callers if needed. if (computation->IsAsyncComputation()) { continue; } for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (removed.contains(instruction)) { // Skip the instruction if it is already removed. continue; } if (flatten_while_loop_ && instruction->opcode() == HloOpcode::kWhile) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(FlattenWhileLoop(instruction, *call_graph)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kInfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveInfeed(instruction)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kOutfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveOutfeed(instruction)); changed = true; } else if (instruction->opcode() == HloOpcode::kSendDone) { auto send_done_instruction = DynCast<HloSendDoneInstruction>(instruction); CHECK(send_done_instruction); if (remove_comm_ || (remove_host_transfer_ && send_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveSendAndSendDone(instruction, &removed).status()); changed = true; } } else if (instruction->opcode() == HloOpcode::kRecvDone) { auto recv_done_instruction = DynCast<HloRecvDoneInstruction>(instruction); CHECK(recv_done_instruction); if (remove_comm_ || (remove_host_transfer_ && recv_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveRecvAndRecvDone(instruction, &removed).status()); changed = true; } } else if (remove_comm_ && IsCollective(instruction) && !instruction->parent()->IsFusionComputation() && (instruction->opcode() != HloOpcode::kAsyncStart && instruction->opcode() != HloOpcode::kAsyncUpdate)) { // We do not remove kAsyncStart or kAsyncUpdate here since we expect // them to be removed as a part of the async chain above. // We should remove the async chain all together because the async // wrapped computation is only associated with the AsyncStart. So we // need to refer to the AsyncStart in order to determine whether // the Done or the Update wraps a collective. if (instruction->opcode() == HloOpcode::kAsyncDone) { while (instruction->opcode() == HloOpcode::kAsyncDone || instruction->opcode() == HloOpcode::kAsyncUpdate || instruction->opcode() == HloOpcode::kAsyncStart) { HloInstruction* operand = instruction->mutable_operand(0); VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); instruction = operand; } } else { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); } changed = true; } else if (remove_comm_ && (instruction->opcode() == HloOpcode::kPartitionId || instruction->opcode() == HloOpcode::kReplicaId || (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == "SliceId"))) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveId(instruction)); changed = true; } } } HloDCE hlo_dce; TF_ASSIGN_OR_RETURN(bool dce_changed, hlo_dce.Run(module, execution_threads)); changed |= dce_changed; // Fix the schedule if the module was scheduled. if (changed && module->has_schedule()) { TF_RETURN_IF_ERROR(module->schedule().Update()); } XLA_VLOG_LINES(3, module->ToString()); return changed; } VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); XLA_VLOG_LINES(3, module->ToString());
#include "xla/tools/hlo_control_flow_flattening.h" #include <memory> #include <utility> #include "absl/strings/str_replace.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/collective_ops_utils.h" #include "xla/service/despecializer.h" #include "xla/service/hlo_verifier.h" #include "xla/service/spmd/spmd_partitioner.h" #include "xla/tests/hlo_test_base.h" #include "tsl/lib/core/status_test_util.h" class HloControlFlowFlatteningTest : public HloTestBase { public: absl::StatusOr<std::unique_ptr<HloModule>> PartitionComputation( std::unique_ptr<VerifiedHloModule> hlo_module, int64_t num_devices = 2) { spmd::SpmdPartitionerOptions options; auto collective_ops_creator = spmd::GetDefaultCollectiveOpsCreator(num_devices, /*num_replicas=*/1); collective_ops_creator.create_cross_partition_all_gather = nullptr; HloModuleConfig config = GetModuleConfigForTest(); config.set_use_spmd_partitioning(true); config.set_num_partitions(num_devices); HloPassPipeline pass("spmd-partitioning"); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); pass.AddPass<spmd::SpmdPartitioner>(num_devices, /*num_replicas=*/1, options, collective_ops_creator); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); TF_RETURN_IF_ERROR(pass.Run(hlo_module.get()).status()); return absl::StatusOr<std::unique_ptr<HloModule>>(std::move(hlo_module)); } }; TEST_F(HloControlFlowFlatteningTest, SendHostTransfer) { absl::string_view hlo_string = R"( HloModule Send ENTRY %Send () -> token[] { %token0 = token[] after-all() %recv = (f32[], u32[], token[]) recv(token[] %token0), channel_id=15 %recv-done = (f32[], token[]) recv-done((f32[], u32[], token[]) %recv), channel_id=15 %constant = f32[] constant(2.1) %send = (f32[], u32[], token[]) send(f32[] %constant, token[] %token0), channel_id=16, is_host_transfer=true, control-predecessors={%recv} ROOT %send-done = token[] send-done((f32[], u32[], token[]) %send), channel_id=16, is_host_transfer=true } )"; TF_ASSERT_OK_AND_ASSIGN(auto module, ParseAndReturnVerifiedModule(hlo_string)); ControlDepRemover control_remover; HloControlFlowFlattening flattening(HloControlFlowFlattening::Options{ /*while_execution_count=*/3, /*max_outer_loop_count=*/3, /*max_loop_count=*/3, /*remove_infeed_outfeed=*/true, /*flatten_while_loop=*/true, /*remove_comm=*/false, /*remove_host_transfer=*/true}); TF_ASSERT_OK(control_remover.Run(module.get()).status()); EXPECT_TRUE(flattening.Run(module.get()).value()); TF_ASSERT_OK(HloVerifier(/*layout_sensitive=*/true, /*allow_mixed_precision=*/true) .Run(module.get()) .status()); EXPECT_THAT(module->entry_computation()->root_instruction(), op::CustomCall(op::CustomCall())); EXPECT_EQ(module->entry_computation()->root_instruction()->name(), "send-done"); EXPECT_EQ(module->entry_computation()->root_instruction()->operand(0)->name(), "send"); }
HloControlFlowFlatteningTest_WhileConditionCallComputation
xla/tools/hlo_control_flow_flattening_test.cc
HloInstruction* CreateConstant(const Shape& shape, HloComputation* computation) { if (shape.IsTuple()) { std::vector<HloInstruction*> tuple_arguments(shape.tuple_shapes_size()); for (int index = 0; index < shape.tuple_shapes_size(); ++index) { tuple_arguments[index] = CreateConstant(shape.tuple_shapes(index), computation); } return computation->AddInstruction( HloInstruction::CreateTuple(tuple_arguments)); } else { return computation->AddInstruction( HloInstruction::CreateConstant(Literal::CreateFromShape(shape))); } } void PrintSubexpression(HloInstruction* inst, int depth) { if (depth == 0) { return; } for (auto* operand : inst->operands()) { PrintSubexpression(operand, depth - 1); } VLOG(2) << inst->ToString(); } VLOG(2) << inst->ToString(); bool IsConstantScalarInt(const HloInstruction* inst) { return inst->opcode() == HloOpcode::kConstant && ShapeUtil::IsEffectiveScalar(inst->shape()) && inst->shape().IsInteger(); } bool IsNotContainedInLoop(const HloInstruction& while_hlo, const CallGraph& call_graph) { const HloComputation* computation = while_hlo.parent(); while (!computation->IsEntryComputation()) { auto& node = call_graph.GetNode(computation); CHECK_EQ(node.caller_callsites().size(), 1) << "The module is not flattened!"; auto& callsite = node.caller_callsites()[0]; if (callsite.instruction()->opcode() == HloOpcode::kWhile) { // Another while loop has been found traversing up the call tree. return false; } computation = callsite.instruction()->parent(); } // No calling while loops were found. return true; } int GetLoopBound(const HloInstruction& while_hlo, const int default_loop_count, const int max_loop_count) { HloInstruction* condition = while_hlo.while_condition()->root_instruction(); if (condition->opcode() == HloOpcode::kCompare) { int64_t value = 0; Comparison::Direction cmp = condition->comparison_direction(); if ((cmp == Comparison::Direction::kLt || cmp == Comparison::Direction::kLe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(1))) { value = *condition->operand(1)->literal().GetFirstInteger(); } else if ((cmp == Comparison::Direction::kGt || cmp == Comparison::Direction::kGe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(0))) { value = *condition->operand(0)->literal().GetFirstInteger(); } if (value > 0) { // Caps to a max loop count to avoid long execution times. return std::min(value, static_cast<int64_t>(max_loop_count)); } } return default_loop_count; } int GetLoopBoundWithOuterLoopMax(const HloInstruction& while_hlo, const CallGraph& call_graph, const int default_loop_count, const int max_outer_loop_count, const int max_loop_count) { int loop_bound = GetLoopBound(while_hlo, default_loop_count, max_loop_count); if (loop_bound > max_outer_loop_count) { // First does the inexpensive loop bound check to avoid as many // expensive graph traversals in IsNotContainedInLoop as possible. if (IsNotContainedInLoop(while_hlo, call_graph)) { return max_outer_loop_count; } } return loop_bound; } absl::Status HloControlFlowFlattening::FlattenWhileLoop( HloInstruction* while_hlo, const CallGraph& call_graph) const { CHECK_EQ(while_hlo->opcode(), HloOpcode::kWhile); HloComputation* computation = while_hlo->parent(); // Add a new induction variable. HloInstruction* initialization = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(0))); // Create a new while operand with the induction variable added. HloInstruction* old_tuple = while_hlo->mutable_operand(0); HloInstruction* new_tuple = TupleUtil::AppendSuffix(old_tuple, {initialization}); int new_tuple_size = new_tuple->shape().tuple_shapes().size(); TF_RETURN_IF_ERROR(while_hlo->ReplaceOperandWithDifferentShape(0, new_tuple)); auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; // Replace the given tuple-shaped instruction of size N in each of its // non-get-tuple-element users with a new tuple instruction which has the // first N - 1 elements. auto replace_non_gte_users = [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; { // Add the new variable to the while loop condition. HloComputation* condition = while_hlo->while_condition(); TF_RETURN_IF_ERROR(change_op_shape(condition->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(condition->parameter_instruction(0)).status()); if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); PrintSubexpression(condition->root_instruction(), /*depth=*/3); } const int loop_bound = GetLoopBoundWithOuterLoopMax( *while_hlo, call_graph, while_execution_count_, max_outer_loop_count_, max_loop_count_); VLOG(1) << "loop_bound = " << loop_bound; HloInstruction* limit = condition->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(loop_bound))); Shape shape = initialization->shape(); HloInstruction* induction_variable = condition->AddInstruction(HloInstruction::CreateGetTupleElement( shape, condition->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* compare = condition->AddInstruction(HloInstruction::CreateCompare( ShapeUtil::MakeShape(PRED, {}), induction_variable, limit, ComparisonDirection::kLt)); TF_RETURN_IF_ERROR( condition->ReplaceInstruction(condition->root_instruction(), compare)); } { // Add the new variable to the while loop body. HloComputation* body = while_hlo->while_body(); TF_RETURN_IF_ERROR(change_op_shape(body->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(body->parameter_instruction(0)).status()); HloInstruction* old_root = body->root_instruction(); Shape shape = initialization->shape(); HloInstruction* induction_variable = body->AddInstruction(HloInstruction::CreateGetTupleElement( shape, body->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* increment = body->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(1))); induction_variable = body->AddInstruction(HloInstruction::CreateBinary( shape, HloOpcode::kAdd, induction_variable, increment)); HloInstruction* new_root = TupleUtil::AppendSuffix(old_root, {induction_variable}); body->set_root_instruction(new_root, /*accept_different_shape=*/true); } // Snapshot the users of while hlo before we add new users. std::vector<HloInstruction*> while_users(while_hlo->users().begin(), while_hlo->users().end()); // Take care of the users of this while loop. TF_RETURN_IF_ERROR(change_op_shape(while_hlo)); TF_ASSIGN_OR_RETURN(HloInstruction * prefix, replace_non_gte_users(while_hlo)); // If the while loop had been the root of its computation, make the prefix new // root. if (while_hlo->parent()->root_instruction() == while_hlo) { // We need to set accept_different_shape=true to reset the root shape to the // original, because we have already changed the shape of the old root // (while). if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix(while_hlo, new_tuple_size - 1); } while_hlo->parent()->set_root_instruction(prefix, /*accept_different_shape=*/true); } return absl::OkStatus(); } auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); VLOG(1) << "loop_bound = " << loop_bound; absl::Status HloControlFlowFlattening::RemoveInfeed( HloInstruction* infeed_hlo) const { CHECK_EQ(infeed_hlo->opcode(), HloOpcode::kInfeed); HloComputation* computation = infeed_hlo->parent(); CHECK_EQ(infeed_hlo->shape().tuple_shapes_size(), 2); const Shape& infeed_shape = ShapeUtil::GetSubshape(infeed_hlo->shape(), {0}); HloInstruction* custom_call = computation->AddInstruction( HloInstruction::CreateCustomCall(infeed_shape, {}, kNopCustomCallTarget)); // Create a new tuple consisting of the constant and the token that was // originally the operand of infeed, and replace the infeed operation. auto new_tuple = HloInstruction::CreateTuple( {custom_call, infeed_hlo->mutable_operand(0)}); TF_RETURN_IF_ERROR( computation->ReplaceWithNewInstruction(infeed_hlo, std::move(new_tuple))); custom_call->SetAndSanitizeName(infeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveRecvAndRecvDone( HloInstruction* recv_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(recv_done->opcode(), HloOpcode::kRecvDone); CHECK_EQ(recv_done->operand_count(), 1); HloInstruction* recv = recv_done->mutable_operand(0); CHECK_EQ(recv->opcode(), HloOpcode::kRecv); HloComputation* computation = recv_done->parent(); CHECK_EQ(recv_done->shape().tuple_shapes_size(), 2); HloModule* module = computation->parent(); HloInstruction* custom_call_recv = computation->AddInstruction(HloInstruction::CreateCustomCall( recv->shape(), recv->operands(), kNopCustomCallTarget)); std::string original_recv_name(recv->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv, custom_call_recv); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(recv, custom_call_recv)); custom_call_recv->SetAndSanitizeName(original_recv_name); std::string original_recv_done_name(recv_done->name()); HloInstruction* custom_call_recv_done = computation->AddInstruction( HloInstruction::CreateCustomCall( recv_done->shape(), recv_done->operands(), kNopCustomCallTarget), recv_done->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv_done, custom_call_recv_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(recv_done, custom_call_recv_done)); custom_call_recv_done->SetAndSanitizeName(original_recv_done_name); return std::make_pair(custom_call_recv, custom_call_recv_done); } absl::Status HloControlFlowFlattening::RemoveOutfeed( HloInstruction* outfeed_hlo) const { CHECK_EQ(outfeed_hlo->opcode(), HloOpcode::kOutfeed); HloComputation* computation = outfeed_hlo->parent(); // Replace the outfeed with a no-op custom call with side effect to ensure the // operands aren't DCE'd. HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( outfeed_hlo->shape(), outfeed_hlo->operands(), kNopReturnTokenCustomCallTarget)); Cast<HloCustomCallInstruction>(custom_call) ->set_custom_call_has_side_effect(true); // For SPMD graphs, partitioner requires that side-effecting custom calls have // a sharding that is non-replicated. custom_call->set_sharding(HloSharding::Manual()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(outfeed_hlo, custom_call)); custom_call->SetAndSanitizeName(outfeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveSendAndSendDone( HloInstruction* send_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(send_done->opcode(), HloOpcode::kSendDone); CHECK_EQ(send_done->operand_count(), 1); HloInstruction* send = send_done->mutable_operand(0); CHECK_EQ(send->opcode(), HloOpcode::kSend); HloComputation* computation = send_done->parent(); HloModule* module = computation->parent(); HloInstruction* custom_call_send = computation->AddInstruction(HloInstruction::CreateCustomCall( send->shape(), send->operands(), kNopCustomCallTarget)); std::string original_send_name(send->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send, custom_call_send); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(send, custom_call_send)); custom_call_send->SetAndSanitizeName(original_send_name); HloInstruction* custom_call_send_done = computation->AddInstruction(HloInstruction::CreateCustomCall( send_done->shape(), send_done->operands(), kNopReturnTokenCustomCallTarget)); std::string original_send_done_name(send_done->name()); Cast<HloCustomCallInstruction>(custom_call_send_done) ->set_custom_call_has_side_effect(true); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send_done, custom_call_send_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(send_done, custom_call_send_done)); custom_call_send_done->SetAndSanitizeName(original_send_done_name); return std::make_pair(custom_call_send, custom_call_send_done); } absl::StatusOr<HloInstruction*> HloControlFlowFlattening::RemoveCollective( HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( hlo->shape(), hlo->operands(), kNopCustomCallTarget)); // Copy backend config. This is necessary for a collective op in megacore // fusion. custom_call->CopyBackendConfigFrom(hlo); HloModule* module = computation->parent(); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, hlo, custom_call); } std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, custom_call)); custom_call->SetAndSanitizeName(original_op_name); return custom_call; } absl::Status HloControlFlowFlattening::RemoveId(HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* zero = CreateConstant(hlo->shape(), computation); std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, zero)); zero->SetAndSanitizeName(original_op_name); return absl::OkStatus(); } absl::StatusOr<bool> HloControlFlowFlattening::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { auto call_graph = CallGraph::Build(module); bool changed = false; absl::flat_hash_set<HloInstruction*> removed; for (HloComputation* computation : module->computations(execution_threads)) { // Do not change computations that are wrapped by async calls. Instead we // remove the async callers if needed. if (computation->IsAsyncComputation()) { continue; } for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (removed.contains(instruction)) { // Skip the instruction if it is already removed. continue; } if (flatten_while_loop_ && instruction->opcode() == HloOpcode::kWhile) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(FlattenWhileLoop(instruction, *call_graph)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kInfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveInfeed(instruction)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kOutfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveOutfeed(instruction)); changed = true; } else if (instruction->opcode() == HloOpcode::kSendDone) { auto send_done_instruction = DynCast<HloSendDoneInstruction>(instruction); CHECK(send_done_instruction); if (remove_comm_ || (remove_host_transfer_ && send_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveSendAndSendDone(instruction, &removed).status()); changed = true; } } else if (instruction->opcode() == HloOpcode::kRecvDone) { auto recv_done_instruction = DynCast<HloRecvDoneInstruction>(instruction); CHECK(recv_done_instruction); if (remove_comm_ || (remove_host_transfer_ && recv_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveRecvAndRecvDone(instruction, &removed).status()); changed = true; } } else if (remove_comm_ && IsCollective(instruction) && !instruction->parent()->IsFusionComputation() && (instruction->opcode() != HloOpcode::kAsyncStart && instruction->opcode() != HloOpcode::kAsyncUpdate)) { // We do not remove kAsyncStart or kAsyncUpdate here since we expect // them to be removed as a part of the async chain above. // We should remove the async chain all together because the async // wrapped computation is only associated with the AsyncStart. So we // need to refer to the AsyncStart in order to determine whether // the Done or the Update wraps a collective. if (instruction->opcode() == HloOpcode::kAsyncDone) { while (instruction->opcode() == HloOpcode::kAsyncDone || instruction->opcode() == HloOpcode::kAsyncUpdate || instruction->opcode() == HloOpcode::kAsyncStart) { HloInstruction* operand = instruction->mutable_operand(0); VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); instruction = operand; } } else { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); } changed = true; } else if (remove_comm_ && (instruction->opcode() == HloOpcode::kPartitionId || instruction->opcode() == HloOpcode::kReplicaId || (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == "SliceId"))) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveId(instruction)); changed = true; } } } HloDCE hlo_dce; TF_ASSIGN_OR_RETURN(bool dce_changed, hlo_dce.Run(module, execution_threads)); changed |= dce_changed; // Fix the schedule if the module was scheduled. if (changed && module->has_schedule()) { TF_RETURN_IF_ERROR(module->schedule().Update()); } XLA_VLOG_LINES(3, module->ToString()); return changed; } VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); XLA_VLOG_LINES(3, module->ToString());
#include "xla/tools/hlo_control_flow_flattening.h" #include <memory> #include <utility> #include "absl/strings/str_replace.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/collective_ops_utils.h" #include "xla/service/despecializer.h" #include "xla/service/hlo_verifier.h" #include "xla/service/spmd/spmd_partitioner.h" #include "xla/tests/hlo_test_base.h" #include "tsl/lib/core/status_test_util.h" class HloControlFlowFlatteningTest : public HloTestBase { public: absl::StatusOr<std::unique_ptr<HloModule>> PartitionComputation( std::unique_ptr<VerifiedHloModule> hlo_module, int64_t num_devices = 2) { spmd::SpmdPartitionerOptions options; auto collective_ops_creator = spmd::GetDefaultCollectiveOpsCreator(num_devices, /*num_replicas=*/1); collective_ops_creator.create_cross_partition_all_gather = nullptr; HloModuleConfig config = GetModuleConfigForTest(); config.set_use_spmd_partitioning(true); config.set_num_partitions(num_devices); HloPassPipeline pass("spmd-partitioning"); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); pass.AddPass<spmd::SpmdPartitioner>(num_devices, /*num_replicas=*/1, options, collective_ops_creator); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); TF_RETURN_IF_ERROR(pass.Run(hlo_module.get()).status()); return absl::StatusOr<std::unique_ptr<HloModule>>(std::move(hlo_module)); } }; TEST_F(HloControlFlowFlatteningTest, WhileConditionCallComputation) { absl::string_view hlo_string = R"( HloModule While While.body { loop_var.1 = (s32[], s32[3]{0}) parameter(0) get-tuple-element.1 = s32[] get-tuple-element(loop_var.1), index=0 constant.1 = s32[] constant(1) add = s32[] add(get-tuple-element.1, constant.1) get-tuple-element.2 = s32[3]{0} get-tuple-element(loop_var.1), index=1 multiply = s32[3]{0} multiply(get-tuple-element.2, get-tuple-element.2) ROOT tuple = (s32[], s32[3]{0}) tuple(add, multiply) } While.condition.called { loop_var.2 = (s32[], s32[3]{0}) parameter(0) get-tuple-element.3 = s32[] get-tuple-element(loop_var.2), index=0 constant.2 = s32[] custom-call(), custom_call_target="AllocateBuffer", custom_call_has_side_effect=true less-than = pred[] compare(get-tuple-element.3, constant.2), direction=LT ROOT tuple.2 = (pred[]) tuple(less-than) } While.condition { loop_var.3 = (s32[], s32[3]{0}) parameter(0) call = (pred[]) call(loop_var.3), to_apply=While.condition.called ROOT get-tuple-element.4 = pred[] get-tuple-element(call), index=0 } ENTRY While { constant.3 = s32[] constant(42) constant.4 = s32[3]{0} constant({0, 1, 2}) tuple.1 = (s32[], s32[3]{0}) tuple(constant.3, constant.4) ROOT while = (s32[], s32[3]{0}) while(tuple.1), condition=While.condition, body=While.body } )"; TF_ASSERT_OK_AND_ASSIGN(auto module, ParseAndReturnVerifiedModule(hlo_string)); HloControlFlowFlattening flattening( HloControlFlowFlattening::Options{/*while_execution_count=*/3}); EXPECT_TRUE(flattening.Run(module.get()).value()); XLA_VLOG_LINES(3, "Loaded HLO module: " + module->ToString()); TF_ASSERT_OK(HloVerifier(/*layout_sensitive=*/true, /*allow_mixed_precision=*/true) .Run(module.get()) .status()); auto root = module->entry_computation()->root_instruction(); auto while_op = module->entry_computation()->GetInstructionWithName("while"); EXPECT_THAT(root, op::Tuple(op::GetTupleElement(while_op, 0), op::GetTupleElement(while_op, 1))); EXPECT_THAT(while_op, op::While(op::Tuple(op::GetTupleElement(), op::GetTupleElement(), op::Constant()))); auto condition = while_op->while_condition(); EXPECT_THAT( condition->root_instruction(), op::Compare(op::GetTupleElement(op::Parameter(0), 2), op::Constant())); auto body = while_op->while_body(); EXPECT_THAT(body->root_instruction(), op::Tuple(op::GetTupleElement(), op::GetTupleElement(), op::Add(op::GetTupleElement(op::Parameter(0), 2), op::Constant()))); }
HloControlFlowFlatteningTest_WhileRoot
xla/tools/hlo_control_flow_flattening_test.cc
HloInstruction* CreateConstant(const Shape& shape, HloComputation* computation) { if (shape.IsTuple()) { std::vector<HloInstruction*> tuple_arguments(shape.tuple_shapes_size()); for (int index = 0; index < shape.tuple_shapes_size(); ++index) { tuple_arguments[index] = CreateConstant(shape.tuple_shapes(index), computation); } return computation->AddInstruction( HloInstruction::CreateTuple(tuple_arguments)); } else { return computation->AddInstruction( HloInstruction::CreateConstant(Literal::CreateFromShape(shape))); } } void PrintSubexpression(HloInstruction* inst, int depth) { if (depth == 0) { return; } for (auto* operand : inst->operands()) { PrintSubexpression(operand, depth - 1); } VLOG(2) << inst->ToString(); } VLOG(2) << inst->ToString(); bool IsConstantScalarInt(const HloInstruction* inst) { return inst->opcode() == HloOpcode::kConstant && ShapeUtil::IsEffectiveScalar(inst->shape()) && inst->shape().IsInteger(); } bool IsNotContainedInLoop(const HloInstruction& while_hlo, const CallGraph& call_graph) { const HloComputation* computation = while_hlo.parent(); while (!computation->IsEntryComputation()) { auto& node = call_graph.GetNode(computation); CHECK_EQ(node.caller_callsites().size(), 1) << "The module is not flattened!"; auto& callsite = node.caller_callsites()[0]; if (callsite.instruction()->opcode() == HloOpcode::kWhile) { // Another while loop has been found traversing up the call tree. return false; } computation = callsite.instruction()->parent(); } // No calling while loops were found. return true; } int GetLoopBound(const HloInstruction& while_hlo, const int default_loop_count, const int max_loop_count) { HloInstruction* condition = while_hlo.while_condition()->root_instruction(); if (condition->opcode() == HloOpcode::kCompare) { int64_t value = 0; Comparison::Direction cmp = condition->comparison_direction(); if ((cmp == Comparison::Direction::kLt || cmp == Comparison::Direction::kLe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(1))) { value = *condition->operand(1)->literal().GetFirstInteger(); } else if ((cmp == Comparison::Direction::kGt || cmp == Comparison::Direction::kGe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(0))) { value = *condition->operand(0)->literal().GetFirstInteger(); } if (value > 0) { // Caps to a max loop count to avoid long execution times. return std::min(value, static_cast<int64_t>(max_loop_count)); } } return default_loop_count; } int GetLoopBoundWithOuterLoopMax(const HloInstruction& while_hlo, const CallGraph& call_graph, const int default_loop_count, const int max_outer_loop_count, const int max_loop_count) { int loop_bound = GetLoopBound(while_hlo, default_loop_count, max_loop_count); if (loop_bound > max_outer_loop_count) { // First does the inexpensive loop bound check to avoid as many // expensive graph traversals in IsNotContainedInLoop as possible. if (IsNotContainedInLoop(while_hlo, call_graph)) { return max_outer_loop_count; } } return loop_bound; } absl::Status HloControlFlowFlattening::FlattenWhileLoop( HloInstruction* while_hlo, const CallGraph& call_graph) const { CHECK_EQ(while_hlo->opcode(), HloOpcode::kWhile); HloComputation* computation = while_hlo->parent(); // Add a new induction variable. HloInstruction* initialization = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(0))); // Create a new while operand with the induction variable added. HloInstruction* old_tuple = while_hlo->mutable_operand(0); HloInstruction* new_tuple = TupleUtil::AppendSuffix(old_tuple, {initialization}); int new_tuple_size = new_tuple->shape().tuple_shapes().size(); TF_RETURN_IF_ERROR(while_hlo->ReplaceOperandWithDifferentShape(0, new_tuple)); auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; // Replace the given tuple-shaped instruction of size N in each of its // non-get-tuple-element users with a new tuple instruction which has the // first N - 1 elements. auto replace_non_gte_users = [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; { // Add the new variable to the while loop condition. HloComputation* condition = while_hlo->while_condition(); TF_RETURN_IF_ERROR(change_op_shape(condition->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(condition->parameter_instruction(0)).status()); if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); PrintSubexpression(condition->root_instruction(), /*depth=*/3); } const int loop_bound = GetLoopBoundWithOuterLoopMax( *while_hlo, call_graph, while_execution_count_, max_outer_loop_count_, max_loop_count_); VLOG(1) << "loop_bound = " << loop_bound; HloInstruction* limit = condition->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(loop_bound))); Shape shape = initialization->shape(); HloInstruction* induction_variable = condition->AddInstruction(HloInstruction::CreateGetTupleElement( shape, condition->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* compare = condition->AddInstruction(HloInstruction::CreateCompare( ShapeUtil::MakeShape(PRED, {}), induction_variable, limit, ComparisonDirection::kLt)); TF_RETURN_IF_ERROR( condition->ReplaceInstruction(condition->root_instruction(), compare)); } { // Add the new variable to the while loop body. HloComputation* body = while_hlo->while_body(); TF_RETURN_IF_ERROR(change_op_shape(body->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(body->parameter_instruction(0)).status()); HloInstruction* old_root = body->root_instruction(); Shape shape = initialization->shape(); HloInstruction* induction_variable = body->AddInstruction(HloInstruction::CreateGetTupleElement( shape, body->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* increment = body->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(1))); induction_variable = body->AddInstruction(HloInstruction::CreateBinary( shape, HloOpcode::kAdd, induction_variable, increment)); HloInstruction* new_root = TupleUtil::AppendSuffix(old_root, {induction_variable}); body->set_root_instruction(new_root, /*accept_different_shape=*/true); } // Snapshot the users of while hlo before we add new users. std::vector<HloInstruction*> while_users(while_hlo->users().begin(), while_hlo->users().end()); // Take care of the users of this while loop. TF_RETURN_IF_ERROR(change_op_shape(while_hlo)); TF_ASSIGN_OR_RETURN(HloInstruction * prefix, replace_non_gte_users(while_hlo)); // If the while loop had been the root of its computation, make the prefix new // root. if (while_hlo->parent()->root_instruction() == while_hlo) { // We need to set accept_different_shape=true to reset the root shape to the // original, because we have already changed the shape of the old root // (while). if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix(while_hlo, new_tuple_size - 1); } while_hlo->parent()->set_root_instruction(prefix, /*accept_different_shape=*/true); } return absl::OkStatus(); } auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); VLOG(1) << "loop_bound = " << loop_bound; absl::Status HloControlFlowFlattening::RemoveInfeed( HloInstruction* infeed_hlo) const { CHECK_EQ(infeed_hlo->opcode(), HloOpcode::kInfeed); HloComputation* computation = infeed_hlo->parent(); CHECK_EQ(infeed_hlo->shape().tuple_shapes_size(), 2); const Shape& infeed_shape = ShapeUtil::GetSubshape(infeed_hlo->shape(), {0}); HloInstruction* custom_call = computation->AddInstruction( HloInstruction::CreateCustomCall(infeed_shape, {}, kNopCustomCallTarget)); // Create a new tuple consisting of the constant and the token that was // originally the operand of infeed, and replace the infeed operation. auto new_tuple = HloInstruction::CreateTuple( {custom_call, infeed_hlo->mutable_operand(0)}); TF_RETURN_IF_ERROR( computation->ReplaceWithNewInstruction(infeed_hlo, std::move(new_tuple))); custom_call->SetAndSanitizeName(infeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveRecvAndRecvDone( HloInstruction* recv_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(recv_done->opcode(), HloOpcode::kRecvDone); CHECK_EQ(recv_done->operand_count(), 1); HloInstruction* recv = recv_done->mutable_operand(0); CHECK_EQ(recv->opcode(), HloOpcode::kRecv); HloComputation* computation = recv_done->parent(); CHECK_EQ(recv_done->shape().tuple_shapes_size(), 2); HloModule* module = computation->parent(); HloInstruction* custom_call_recv = computation->AddInstruction(HloInstruction::CreateCustomCall( recv->shape(), recv->operands(), kNopCustomCallTarget)); std::string original_recv_name(recv->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv, custom_call_recv); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(recv, custom_call_recv)); custom_call_recv->SetAndSanitizeName(original_recv_name); std::string original_recv_done_name(recv_done->name()); HloInstruction* custom_call_recv_done = computation->AddInstruction( HloInstruction::CreateCustomCall( recv_done->shape(), recv_done->operands(), kNopCustomCallTarget), recv_done->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv_done, custom_call_recv_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(recv_done, custom_call_recv_done)); custom_call_recv_done->SetAndSanitizeName(original_recv_done_name); return std::make_pair(custom_call_recv, custom_call_recv_done); } absl::Status HloControlFlowFlattening::RemoveOutfeed( HloInstruction* outfeed_hlo) const { CHECK_EQ(outfeed_hlo->opcode(), HloOpcode::kOutfeed); HloComputation* computation = outfeed_hlo->parent(); // Replace the outfeed with a no-op custom call with side effect to ensure the // operands aren't DCE'd. HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( outfeed_hlo->shape(), outfeed_hlo->operands(), kNopReturnTokenCustomCallTarget)); Cast<HloCustomCallInstruction>(custom_call) ->set_custom_call_has_side_effect(true); // For SPMD graphs, partitioner requires that side-effecting custom calls have // a sharding that is non-replicated. custom_call->set_sharding(HloSharding::Manual()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(outfeed_hlo, custom_call)); custom_call->SetAndSanitizeName(outfeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveSendAndSendDone( HloInstruction* send_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(send_done->opcode(), HloOpcode::kSendDone); CHECK_EQ(send_done->operand_count(), 1); HloInstruction* send = send_done->mutable_operand(0); CHECK_EQ(send->opcode(), HloOpcode::kSend); HloComputation* computation = send_done->parent(); HloModule* module = computation->parent(); HloInstruction* custom_call_send = computation->AddInstruction(HloInstruction::CreateCustomCall( send->shape(), send->operands(), kNopCustomCallTarget)); std::string original_send_name(send->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send, custom_call_send); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(send, custom_call_send)); custom_call_send->SetAndSanitizeName(original_send_name); HloInstruction* custom_call_send_done = computation->AddInstruction(HloInstruction::CreateCustomCall( send_done->shape(), send_done->operands(), kNopReturnTokenCustomCallTarget)); std::string original_send_done_name(send_done->name()); Cast<HloCustomCallInstruction>(custom_call_send_done) ->set_custom_call_has_side_effect(true); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send_done, custom_call_send_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(send_done, custom_call_send_done)); custom_call_send_done->SetAndSanitizeName(original_send_done_name); return std::make_pair(custom_call_send, custom_call_send_done); } absl::StatusOr<HloInstruction*> HloControlFlowFlattening::RemoveCollective( HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( hlo->shape(), hlo->operands(), kNopCustomCallTarget)); // Copy backend config. This is necessary for a collective op in megacore // fusion. custom_call->CopyBackendConfigFrom(hlo); HloModule* module = computation->parent(); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, hlo, custom_call); } std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, custom_call)); custom_call->SetAndSanitizeName(original_op_name); return custom_call; } absl::Status HloControlFlowFlattening::RemoveId(HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* zero = CreateConstant(hlo->shape(), computation); std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, zero)); zero->SetAndSanitizeName(original_op_name); return absl::OkStatus(); } absl::StatusOr<bool> HloControlFlowFlattening::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { auto call_graph = CallGraph::Build(module); bool changed = false; absl::flat_hash_set<HloInstruction*> removed; for (HloComputation* computation : module->computations(execution_threads)) { // Do not change computations that are wrapped by async calls. Instead we // remove the async callers if needed. if (computation->IsAsyncComputation()) { continue; } for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (removed.contains(instruction)) { // Skip the instruction if it is already removed. continue; } if (flatten_while_loop_ && instruction->opcode() == HloOpcode::kWhile) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(FlattenWhileLoop(instruction, *call_graph)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kInfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveInfeed(instruction)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kOutfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveOutfeed(instruction)); changed = true; } else if (instruction->opcode() == HloOpcode::kSendDone) { auto send_done_instruction = DynCast<HloSendDoneInstruction>(instruction); CHECK(send_done_instruction); if (remove_comm_ || (remove_host_transfer_ && send_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveSendAndSendDone(instruction, &removed).status()); changed = true; } } else if (instruction->opcode() == HloOpcode::kRecvDone) { auto recv_done_instruction = DynCast<HloRecvDoneInstruction>(instruction); CHECK(recv_done_instruction); if (remove_comm_ || (remove_host_transfer_ && recv_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveRecvAndRecvDone(instruction, &removed).status()); changed = true; } } else if (remove_comm_ && IsCollective(instruction) && !instruction->parent()->IsFusionComputation() && (instruction->opcode() != HloOpcode::kAsyncStart && instruction->opcode() != HloOpcode::kAsyncUpdate)) { // We do not remove kAsyncStart or kAsyncUpdate here since we expect // them to be removed as a part of the async chain above. // We should remove the async chain all together because the async // wrapped computation is only associated with the AsyncStart. So we // need to refer to the AsyncStart in order to determine whether // the Done or the Update wraps a collective. if (instruction->opcode() == HloOpcode::kAsyncDone) { while (instruction->opcode() == HloOpcode::kAsyncDone || instruction->opcode() == HloOpcode::kAsyncUpdate || instruction->opcode() == HloOpcode::kAsyncStart) { HloInstruction* operand = instruction->mutable_operand(0); VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); instruction = operand; } } else { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); } changed = true; } else if (remove_comm_ && (instruction->opcode() == HloOpcode::kPartitionId || instruction->opcode() == HloOpcode::kReplicaId || (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == "SliceId"))) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveId(instruction)); changed = true; } } } HloDCE hlo_dce; TF_ASSIGN_OR_RETURN(bool dce_changed, hlo_dce.Run(module, execution_threads)); changed |= dce_changed; // Fix the schedule if the module was scheduled. if (changed && module->has_schedule()) { TF_RETURN_IF_ERROR(module->schedule().Update()); } XLA_VLOG_LINES(3, module->ToString()); return changed; } VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); XLA_VLOG_LINES(3, module->ToString());
#include "xla/tools/hlo_control_flow_flattening.h" #include <memory> #include <utility> #include "absl/strings/str_replace.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/collective_ops_utils.h" #include "xla/service/despecializer.h" #include "xla/service/hlo_verifier.h" #include "xla/service/spmd/spmd_partitioner.h" #include "xla/tests/hlo_test_base.h" #include "tsl/lib/core/status_test_util.h" class HloControlFlowFlatteningTest : public HloTestBase { public: absl::StatusOr<std::unique_ptr<HloModule>> PartitionComputation( std::unique_ptr<VerifiedHloModule> hlo_module, int64_t num_devices = 2) { spmd::SpmdPartitionerOptions options; auto collective_ops_creator = spmd::GetDefaultCollectiveOpsCreator(num_devices, /*num_replicas=*/1); collective_ops_creator.create_cross_partition_all_gather = nullptr; HloModuleConfig config = GetModuleConfigForTest(); config.set_use_spmd_partitioning(true); config.set_num_partitions(num_devices); HloPassPipeline pass("spmd-partitioning"); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); pass.AddPass<spmd::SpmdPartitioner>(num_devices, /*num_replicas=*/1, options, collective_ops_creator); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); TF_RETURN_IF_ERROR(pass.Run(hlo_module.get()).status()); return absl::StatusOr<std::unique_ptr<HloModule>>(std::move(hlo_module)); } }; TEST_F(HloControlFlowFlatteningTest, WhileRoot) { absl::string_view hlo_string = R"( HloModule While While.body { loop_var.1 = (s32[], s32[3]{0}) parameter(0) get-tuple-element.1 = s32[] get-tuple-element(loop_var.1), index=0 constant.1 = s32[] constant(1) add = s32[] add(get-tuple-element.1, constant.1) get-tuple-element.2 = s32[3]{0} get-tuple-element(loop_var.1), index=1 multiply = s32[3]{0} multiply(get-tuple-element.2, get-tuple-element.2) ROOT tuple = (s32[], s32[3]{0}) tuple(add, multiply) } While.condition { loop_var.2 = (s32[], s32[3]{0}) parameter(0) get-tuple-element.3 = s32[] get-tuple-element(loop_var.2), index=0 constant.2 = s32[] constant(100) ROOT less-than = pred[] compare(get-tuple-element.3, constant.2), direction=LT } ENTRY While { constant.3 = s32[] constant(42) constant.4 = s32[3]{0} constant({0, 1, 2}) tuple.1 = (s32[], s32[3]{0}) tuple(constant.3, constant.4) ROOT while = (s32[], s32[3]{0}) while(tuple.1), condition=While.condition, body=While.body } )"; TF_ASSERT_OK_AND_ASSIGN(auto module, ParseAndReturnVerifiedModule(hlo_string)); HloControlFlowFlattening flattening( HloControlFlowFlattening::Options{/*while_execution_count=*/3}); EXPECT_TRUE(flattening.Run(module.get()).value()); TF_ASSERT_OK(HloVerifier(/*layout_sensitive=*/true, /*allow_mixed_precision=*/true) .Run(module.get()) .status()); auto root = module->entry_computation()->root_instruction(); auto while_op = module->entry_computation()->GetInstructionWithName("while"); EXPECT_THAT(root, op::Tuple(op::GetTupleElement(while_op, 0), op::GetTupleElement(while_op, 1))); EXPECT_THAT(while_op, op::While(op::Tuple(op::GetTupleElement(), op::GetTupleElement(), op::Constant()))); auto condition = while_op->while_condition(); EXPECT_THAT( condition->root_instruction(), op::Compare(op::GetTupleElement(op::Parameter(0), 2), op::Constant())); auto body = while_op->while_body(); EXPECT_THAT(body->root_instruction(), op::Tuple(op::GetTupleElement(), op::GetTupleElement(), op::Add(op::GetTupleElement(op::Parameter(0), 2), op::Constant()))); }
HloControlFlowFlatteningTest_WhileRootScheduled
xla/tools/hlo_control_flow_flattening_test.cc
HloInstruction* CreateConstant(const Shape& shape, HloComputation* computation) { if (shape.IsTuple()) { std::vector<HloInstruction*> tuple_arguments(shape.tuple_shapes_size()); for (int index = 0; index < shape.tuple_shapes_size(); ++index) { tuple_arguments[index] = CreateConstant(shape.tuple_shapes(index), computation); } return computation->AddInstruction( HloInstruction::CreateTuple(tuple_arguments)); } else { return computation->AddInstruction( HloInstruction::CreateConstant(Literal::CreateFromShape(shape))); } } void PrintSubexpression(HloInstruction* inst, int depth) { if (depth == 0) { return; } for (auto* operand : inst->operands()) { PrintSubexpression(operand, depth - 1); } VLOG(2) << inst->ToString(); } VLOG(2) << inst->ToString(); bool IsConstantScalarInt(const HloInstruction* inst) { return inst->opcode() == HloOpcode::kConstant && ShapeUtil::IsEffectiveScalar(inst->shape()) && inst->shape().IsInteger(); } bool IsNotContainedInLoop(const HloInstruction& while_hlo, const CallGraph& call_graph) { const HloComputation* computation = while_hlo.parent(); while (!computation->IsEntryComputation()) { auto& node = call_graph.GetNode(computation); CHECK_EQ(node.caller_callsites().size(), 1) << "The module is not flattened!"; auto& callsite = node.caller_callsites()[0]; if (callsite.instruction()->opcode() == HloOpcode::kWhile) { // Another while loop has been found traversing up the call tree. return false; } computation = callsite.instruction()->parent(); } // No calling while loops were found. return true; } int GetLoopBound(const HloInstruction& while_hlo, const int default_loop_count, const int max_loop_count) { HloInstruction* condition = while_hlo.while_condition()->root_instruction(); if (condition->opcode() == HloOpcode::kCompare) { int64_t value = 0; Comparison::Direction cmp = condition->comparison_direction(); if ((cmp == Comparison::Direction::kLt || cmp == Comparison::Direction::kLe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(1))) { value = *condition->operand(1)->literal().GetFirstInteger(); } else if ((cmp == Comparison::Direction::kGt || cmp == Comparison::Direction::kGe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(0))) { value = *condition->operand(0)->literal().GetFirstInteger(); } if (value > 0) { // Caps to a max loop count to avoid long execution times. return std::min(value, static_cast<int64_t>(max_loop_count)); } } return default_loop_count; } int GetLoopBoundWithOuterLoopMax(const HloInstruction& while_hlo, const CallGraph& call_graph, const int default_loop_count, const int max_outer_loop_count, const int max_loop_count) { int loop_bound = GetLoopBound(while_hlo, default_loop_count, max_loop_count); if (loop_bound > max_outer_loop_count) { // First does the inexpensive loop bound check to avoid as many // expensive graph traversals in IsNotContainedInLoop as possible. if (IsNotContainedInLoop(while_hlo, call_graph)) { return max_outer_loop_count; } } return loop_bound; } absl::Status HloControlFlowFlattening::FlattenWhileLoop( HloInstruction* while_hlo, const CallGraph& call_graph) const { CHECK_EQ(while_hlo->opcode(), HloOpcode::kWhile); HloComputation* computation = while_hlo->parent(); // Add a new induction variable. HloInstruction* initialization = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(0))); // Create a new while operand with the induction variable added. HloInstruction* old_tuple = while_hlo->mutable_operand(0); HloInstruction* new_tuple = TupleUtil::AppendSuffix(old_tuple, {initialization}); int new_tuple_size = new_tuple->shape().tuple_shapes().size(); TF_RETURN_IF_ERROR(while_hlo->ReplaceOperandWithDifferentShape(0, new_tuple)); auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; // Replace the given tuple-shaped instruction of size N in each of its // non-get-tuple-element users with a new tuple instruction which has the // first N - 1 elements. auto replace_non_gte_users = [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; { // Add the new variable to the while loop condition. HloComputation* condition = while_hlo->while_condition(); TF_RETURN_IF_ERROR(change_op_shape(condition->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(condition->parameter_instruction(0)).status()); if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); PrintSubexpression(condition->root_instruction(), /*depth=*/3); } const int loop_bound = GetLoopBoundWithOuterLoopMax( *while_hlo, call_graph, while_execution_count_, max_outer_loop_count_, max_loop_count_); VLOG(1) << "loop_bound = " << loop_bound; HloInstruction* limit = condition->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(loop_bound))); Shape shape = initialization->shape(); HloInstruction* induction_variable = condition->AddInstruction(HloInstruction::CreateGetTupleElement( shape, condition->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* compare = condition->AddInstruction(HloInstruction::CreateCompare( ShapeUtil::MakeShape(PRED, {}), induction_variable, limit, ComparisonDirection::kLt)); TF_RETURN_IF_ERROR( condition->ReplaceInstruction(condition->root_instruction(), compare)); } { // Add the new variable to the while loop body. HloComputation* body = while_hlo->while_body(); TF_RETURN_IF_ERROR(change_op_shape(body->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(body->parameter_instruction(0)).status()); HloInstruction* old_root = body->root_instruction(); Shape shape = initialization->shape(); HloInstruction* induction_variable = body->AddInstruction(HloInstruction::CreateGetTupleElement( shape, body->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* increment = body->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(1))); induction_variable = body->AddInstruction(HloInstruction::CreateBinary( shape, HloOpcode::kAdd, induction_variable, increment)); HloInstruction* new_root = TupleUtil::AppendSuffix(old_root, {induction_variable}); body->set_root_instruction(new_root, /*accept_different_shape=*/true); } // Snapshot the users of while hlo before we add new users. std::vector<HloInstruction*> while_users(while_hlo->users().begin(), while_hlo->users().end()); // Take care of the users of this while loop. TF_RETURN_IF_ERROR(change_op_shape(while_hlo)); TF_ASSIGN_OR_RETURN(HloInstruction * prefix, replace_non_gte_users(while_hlo)); // If the while loop had been the root of its computation, make the prefix new // root. if (while_hlo->parent()->root_instruction() == while_hlo) { // We need to set accept_different_shape=true to reset the root shape to the // original, because we have already changed the shape of the old root // (while). if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix(while_hlo, new_tuple_size - 1); } while_hlo->parent()->set_root_instruction(prefix, /*accept_different_shape=*/true); } return absl::OkStatus(); } auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); VLOG(1) << "loop_bound = " << loop_bound; absl::Status HloControlFlowFlattening::RemoveInfeed( HloInstruction* infeed_hlo) const { CHECK_EQ(infeed_hlo->opcode(), HloOpcode::kInfeed); HloComputation* computation = infeed_hlo->parent(); CHECK_EQ(infeed_hlo->shape().tuple_shapes_size(), 2); const Shape& infeed_shape = ShapeUtil::GetSubshape(infeed_hlo->shape(), {0}); HloInstruction* custom_call = computation->AddInstruction( HloInstruction::CreateCustomCall(infeed_shape, {}, kNopCustomCallTarget)); // Create a new tuple consisting of the constant and the token that was // originally the operand of infeed, and replace the infeed operation. auto new_tuple = HloInstruction::CreateTuple( {custom_call, infeed_hlo->mutable_operand(0)}); TF_RETURN_IF_ERROR( computation->ReplaceWithNewInstruction(infeed_hlo, std::move(new_tuple))); custom_call->SetAndSanitizeName(infeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveRecvAndRecvDone( HloInstruction* recv_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(recv_done->opcode(), HloOpcode::kRecvDone); CHECK_EQ(recv_done->operand_count(), 1); HloInstruction* recv = recv_done->mutable_operand(0); CHECK_EQ(recv->opcode(), HloOpcode::kRecv); HloComputation* computation = recv_done->parent(); CHECK_EQ(recv_done->shape().tuple_shapes_size(), 2); HloModule* module = computation->parent(); HloInstruction* custom_call_recv = computation->AddInstruction(HloInstruction::CreateCustomCall( recv->shape(), recv->operands(), kNopCustomCallTarget)); std::string original_recv_name(recv->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv, custom_call_recv); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(recv, custom_call_recv)); custom_call_recv->SetAndSanitizeName(original_recv_name); std::string original_recv_done_name(recv_done->name()); HloInstruction* custom_call_recv_done = computation->AddInstruction( HloInstruction::CreateCustomCall( recv_done->shape(), recv_done->operands(), kNopCustomCallTarget), recv_done->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv_done, custom_call_recv_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(recv_done, custom_call_recv_done)); custom_call_recv_done->SetAndSanitizeName(original_recv_done_name); return std::make_pair(custom_call_recv, custom_call_recv_done); } absl::Status HloControlFlowFlattening::RemoveOutfeed( HloInstruction* outfeed_hlo) const { CHECK_EQ(outfeed_hlo->opcode(), HloOpcode::kOutfeed); HloComputation* computation = outfeed_hlo->parent(); // Replace the outfeed with a no-op custom call with side effect to ensure the // operands aren't DCE'd. HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( outfeed_hlo->shape(), outfeed_hlo->operands(), kNopReturnTokenCustomCallTarget)); Cast<HloCustomCallInstruction>(custom_call) ->set_custom_call_has_side_effect(true); // For SPMD graphs, partitioner requires that side-effecting custom calls have // a sharding that is non-replicated. custom_call->set_sharding(HloSharding::Manual()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(outfeed_hlo, custom_call)); custom_call->SetAndSanitizeName(outfeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveSendAndSendDone( HloInstruction* send_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(send_done->opcode(), HloOpcode::kSendDone); CHECK_EQ(send_done->operand_count(), 1); HloInstruction* send = send_done->mutable_operand(0); CHECK_EQ(send->opcode(), HloOpcode::kSend); HloComputation* computation = send_done->parent(); HloModule* module = computation->parent(); HloInstruction* custom_call_send = computation->AddInstruction(HloInstruction::CreateCustomCall( send->shape(), send->operands(), kNopCustomCallTarget)); std::string original_send_name(send->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send, custom_call_send); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(send, custom_call_send)); custom_call_send->SetAndSanitizeName(original_send_name); HloInstruction* custom_call_send_done = computation->AddInstruction(HloInstruction::CreateCustomCall( send_done->shape(), send_done->operands(), kNopReturnTokenCustomCallTarget)); std::string original_send_done_name(send_done->name()); Cast<HloCustomCallInstruction>(custom_call_send_done) ->set_custom_call_has_side_effect(true); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send_done, custom_call_send_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(send_done, custom_call_send_done)); custom_call_send_done->SetAndSanitizeName(original_send_done_name); return std::make_pair(custom_call_send, custom_call_send_done); } absl::StatusOr<HloInstruction*> HloControlFlowFlattening::RemoveCollective( HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( hlo->shape(), hlo->operands(), kNopCustomCallTarget)); // Copy backend config. This is necessary for a collective op in megacore // fusion. custom_call->CopyBackendConfigFrom(hlo); HloModule* module = computation->parent(); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, hlo, custom_call); } std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, custom_call)); custom_call->SetAndSanitizeName(original_op_name); return custom_call; } absl::Status HloControlFlowFlattening::RemoveId(HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* zero = CreateConstant(hlo->shape(), computation); std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, zero)); zero->SetAndSanitizeName(original_op_name); return absl::OkStatus(); } absl::StatusOr<bool> HloControlFlowFlattening::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { auto call_graph = CallGraph::Build(module); bool changed = false; absl::flat_hash_set<HloInstruction*> removed; for (HloComputation* computation : module->computations(execution_threads)) { // Do not change computations that are wrapped by async calls. Instead we // remove the async callers if needed. if (computation->IsAsyncComputation()) { continue; } for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (removed.contains(instruction)) { // Skip the instruction if it is already removed. continue; } if (flatten_while_loop_ && instruction->opcode() == HloOpcode::kWhile) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(FlattenWhileLoop(instruction, *call_graph)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kInfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveInfeed(instruction)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kOutfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveOutfeed(instruction)); changed = true; } else if (instruction->opcode() == HloOpcode::kSendDone) { auto send_done_instruction = DynCast<HloSendDoneInstruction>(instruction); CHECK(send_done_instruction); if (remove_comm_ || (remove_host_transfer_ && send_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveSendAndSendDone(instruction, &removed).status()); changed = true; } } else if (instruction->opcode() == HloOpcode::kRecvDone) { auto recv_done_instruction = DynCast<HloRecvDoneInstruction>(instruction); CHECK(recv_done_instruction); if (remove_comm_ || (remove_host_transfer_ && recv_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveRecvAndRecvDone(instruction, &removed).status()); changed = true; } } else if (remove_comm_ && IsCollective(instruction) && !instruction->parent()->IsFusionComputation() && (instruction->opcode() != HloOpcode::kAsyncStart && instruction->opcode() != HloOpcode::kAsyncUpdate)) { // We do not remove kAsyncStart or kAsyncUpdate here since we expect // them to be removed as a part of the async chain above. // We should remove the async chain all together because the async // wrapped computation is only associated with the AsyncStart. So we // need to refer to the AsyncStart in order to determine whether // the Done or the Update wraps a collective. if (instruction->opcode() == HloOpcode::kAsyncDone) { while (instruction->opcode() == HloOpcode::kAsyncDone || instruction->opcode() == HloOpcode::kAsyncUpdate || instruction->opcode() == HloOpcode::kAsyncStart) { HloInstruction* operand = instruction->mutable_operand(0); VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); instruction = operand; } } else { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); } changed = true; } else if (remove_comm_ && (instruction->opcode() == HloOpcode::kPartitionId || instruction->opcode() == HloOpcode::kReplicaId || (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == "SliceId"))) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveId(instruction)); changed = true; } } } HloDCE hlo_dce; TF_ASSIGN_OR_RETURN(bool dce_changed, hlo_dce.Run(module, execution_threads)); changed |= dce_changed; // Fix the schedule if the module was scheduled. if (changed && module->has_schedule()) { TF_RETURN_IF_ERROR(module->schedule().Update()); } XLA_VLOG_LINES(3, module->ToString()); return changed; } VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); XLA_VLOG_LINES(3, module->ToString());
#include "xla/tools/hlo_control_flow_flattening.h" #include <memory> #include <utility> #include "absl/strings/str_replace.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/collective_ops_utils.h" #include "xla/service/despecializer.h" #include "xla/service/hlo_verifier.h" #include "xla/service/spmd/spmd_partitioner.h" #include "xla/tests/hlo_test_base.h" #include "tsl/lib/core/status_test_util.h" class HloControlFlowFlatteningTest : public HloTestBase { public: absl::StatusOr<std::unique_ptr<HloModule>> PartitionComputation( std::unique_ptr<VerifiedHloModule> hlo_module, int64_t num_devices = 2) { spmd::SpmdPartitionerOptions options; auto collective_ops_creator = spmd::GetDefaultCollectiveOpsCreator(num_devices, /*num_replicas=*/1); collective_ops_creator.create_cross_partition_all_gather = nullptr; HloModuleConfig config = GetModuleConfigForTest(); config.set_use_spmd_partitioning(true); config.set_num_partitions(num_devices); HloPassPipeline pass("spmd-partitioning"); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); pass.AddPass<spmd::SpmdPartitioner>(num_devices, /*num_replicas=*/1, options, collective_ops_creator); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); TF_RETURN_IF_ERROR(pass.Run(hlo_module.get()).status()); return absl::StatusOr<std::unique_ptr<HloModule>>(std::move(hlo_module)); } }; TEST_F(HloControlFlowFlatteningTest, WhileRootScheduled) { absl::string_view hlo_string = R"( HloModule While, is_scheduled=true While.body { loop_var.1 = (s32[], s32[3]{0}) parameter(0) get-tuple-element.1 = s32[] get-tuple-element(loop_var.1), index=0 constant.1 = s32[] constant(1) add = s32[] add(get-tuple-element.1, constant.1) get-tuple-element.2 = s32[3]{0} get-tuple-element(loop_var.1), index=1 multiply = s32[3]{0} multiply(get-tuple-element.2, get-tuple-element.2) ROOT tuple = (s32[], s32[3]{0}) tuple(add, multiply) } While.condition { loop_var.2 = (s32[], s32[3]{0}) parameter(0) get-tuple-element.3 = s32[] get-tuple-element(loop_var.2), index=0 constant.2 = s32[] constant(100) ROOT less-than = pred[] compare(get-tuple-element.3, constant.2), direction=LT } ENTRY While { constant.3 = s32[] constant(42) constant.4 = s32[3]{0} constant({0, 1, 2}) tuple.1 = (s32[], s32[3]{0}) tuple(constant.3, constant.4) ROOT while = (s32[], s32[3]{0}) while(tuple.1), condition=While.condition, body=While.body } )"; TF_ASSERT_OK_AND_ASSIGN(auto module, ParseAndReturnVerifiedModule(hlo_string)); HloControlFlowFlattening flattening( HloControlFlowFlattening::Options{/*while_execution_count=*/3}); EXPECT_TRUE(flattening.Run(module.get()).value()); TF_ASSERT_OK(HloVerifier(/*layout_sensitive=*/true, /*allow_mixed_precision=*/true) .Run(module.get()) .status()); auto root = module->entry_computation()->root_instruction(); auto while_op = module->entry_computation()->GetInstructionWithName("while"); EXPECT_THAT(root, op::Tuple(op::GetTupleElement(while_op, 0), op::GetTupleElement(while_op, 1))); EXPECT_THAT(while_op, op::While(op::Tuple(op::GetTupleElement(), op::GetTupleElement(), op::Constant()))); auto condition = while_op->while_condition(); EXPECT_THAT( condition->root_instruction(), op::Compare(op::GetTupleElement(op::Parameter(0), 2), op::Constant())); }
HloControlFlowFlatteningTest_WhileUser
xla/tools/hlo_control_flow_flattening_test.cc
HloInstruction* CreateConstant(const Shape& shape, HloComputation* computation) { if (shape.IsTuple()) { std::vector<HloInstruction*> tuple_arguments(shape.tuple_shapes_size()); for (int index = 0; index < shape.tuple_shapes_size(); ++index) { tuple_arguments[index] = CreateConstant(shape.tuple_shapes(index), computation); } return computation->AddInstruction( HloInstruction::CreateTuple(tuple_arguments)); } else { return computation->AddInstruction( HloInstruction::CreateConstant(Literal::CreateFromShape(shape))); } } void PrintSubexpression(HloInstruction* inst, int depth) { if (depth == 0) { return; } for (auto* operand : inst->operands()) { PrintSubexpression(operand, depth - 1); } VLOG(2) << inst->ToString(); } VLOG(2) << inst->ToString(); bool IsConstantScalarInt(const HloInstruction* inst) { return inst->opcode() == HloOpcode::kConstant && ShapeUtil::IsEffectiveScalar(inst->shape()) && inst->shape().IsInteger(); } bool IsNotContainedInLoop(const HloInstruction& while_hlo, const CallGraph& call_graph) { const HloComputation* computation = while_hlo.parent(); while (!computation->IsEntryComputation()) { auto& node = call_graph.GetNode(computation); CHECK_EQ(node.caller_callsites().size(), 1) << "The module is not flattened!"; auto& callsite = node.caller_callsites()[0]; if (callsite.instruction()->opcode() == HloOpcode::kWhile) { // Another while loop has been found traversing up the call tree. return false; } computation = callsite.instruction()->parent(); } // No calling while loops were found. return true; } int GetLoopBound(const HloInstruction& while_hlo, const int default_loop_count, const int max_loop_count) { HloInstruction* condition = while_hlo.while_condition()->root_instruction(); if (condition->opcode() == HloOpcode::kCompare) { int64_t value = 0; Comparison::Direction cmp = condition->comparison_direction(); if ((cmp == Comparison::Direction::kLt || cmp == Comparison::Direction::kLe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(1))) { value = *condition->operand(1)->literal().GetFirstInteger(); } else if ((cmp == Comparison::Direction::kGt || cmp == Comparison::Direction::kGe || cmp == Comparison::Direction::kNe) && IsConstantScalarInt(condition->operand(0))) { value = *condition->operand(0)->literal().GetFirstInteger(); } if (value > 0) { // Caps to a max loop count to avoid long execution times. return std::min(value, static_cast<int64_t>(max_loop_count)); } } return default_loop_count; } int GetLoopBoundWithOuterLoopMax(const HloInstruction& while_hlo, const CallGraph& call_graph, const int default_loop_count, const int max_outer_loop_count, const int max_loop_count) { int loop_bound = GetLoopBound(while_hlo, default_loop_count, max_loop_count); if (loop_bound > max_outer_loop_count) { // First does the inexpensive loop bound check to avoid as many // expensive graph traversals in IsNotContainedInLoop as possible. if (IsNotContainedInLoop(while_hlo, call_graph)) { return max_outer_loop_count; } } return loop_bound; } absl::Status HloControlFlowFlattening::FlattenWhileLoop( HloInstruction* while_hlo, const CallGraph& call_graph) const { CHECK_EQ(while_hlo->opcode(), HloOpcode::kWhile); HloComputation* computation = while_hlo->parent(); // Add a new induction variable. HloInstruction* initialization = computation->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(0))); // Create a new while operand with the induction variable added. HloInstruction* old_tuple = while_hlo->mutable_operand(0); HloInstruction* new_tuple = TupleUtil::AppendSuffix(old_tuple, {initialization}); int new_tuple_size = new_tuple->shape().tuple_shapes().size(); TF_RETURN_IF_ERROR(while_hlo->ReplaceOperandWithDifferentShape(0, new_tuple)); auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; // Replace the given tuple-shaped instruction of size N in each of its // non-get-tuple-element users with a new tuple instruction which has the // first N - 1 elements. auto replace_non_gte_users = [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; { // Add the new variable to the while loop condition. HloComputation* condition = while_hlo->while_condition(); TF_RETURN_IF_ERROR(change_op_shape(condition->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(condition->parameter_instruction(0)).status()); if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); PrintSubexpression(condition->root_instruction(), /*depth=*/3); } const int loop_bound = GetLoopBoundWithOuterLoopMax( *while_hlo, call_graph, while_execution_count_, max_outer_loop_count_, max_loop_count_); VLOG(1) << "loop_bound = " << loop_bound; HloInstruction* limit = condition->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(loop_bound))); Shape shape = initialization->shape(); HloInstruction* induction_variable = condition->AddInstruction(HloInstruction::CreateGetTupleElement( shape, condition->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* compare = condition->AddInstruction(HloInstruction::CreateCompare( ShapeUtil::MakeShape(PRED, {}), induction_variable, limit, ComparisonDirection::kLt)); TF_RETURN_IF_ERROR( condition->ReplaceInstruction(condition->root_instruction(), compare)); } { // Add the new variable to the while loop body. HloComputation* body = while_hlo->while_body(); TF_RETURN_IF_ERROR(change_op_shape(body->parameter_instruction(0))); TF_RETURN_IF_ERROR( replace_non_gte_users(body->parameter_instruction(0)).status()); HloInstruction* old_root = body->root_instruction(); Shape shape = initialization->shape(); HloInstruction* induction_variable = body->AddInstruction(HloInstruction::CreateGetTupleElement( shape, body->parameter_instruction(0), new_tuple_size - 1)); HloInstruction* increment = body->AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int>(1))); induction_variable = body->AddInstruction(HloInstruction::CreateBinary( shape, HloOpcode::kAdd, induction_variable, increment)); HloInstruction* new_root = TupleUtil::AppendSuffix(old_root, {induction_variable}); body->set_root_instruction(new_root, /*accept_different_shape=*/true); } // Snapshot the users of while hlo before we add new users. std::vector<HloInstruction*> while_users(while_hlo->users().begin(), while_hlo->users().end()); // Take care of the users of this while loop. TF_RETURN_IF_ERROR(change_op_shape(while_hlo)); TF_ASSIGN_OR_RETURN(HloInstruction * prefix, replace_non_gte_users(while_hlo)); // If the while loop had been the root of its computation, make the prefix new // root. if (while_hlo->parent()->root_instruction() == while_hlo) { // We need to set accept_different_shape=true to reset the root shape to the // original, because we have already changed the shape of the old root // (while). if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix(while_hlo, new_tuple_size - 1); } while_hlo->parent()->set_root_instruction(prefix, /*accept_different_shape=*/true); } return absl::OkStatus(); } auto change_op_shape = [&](HloInstruction* instruction) { Shape* shape = instruction->mutable_shape(); CHECK(shape->IsTuple()); CHECK_EQ(shape->tuple_shapes().size(), new_tuple_size - 1); Shape* subshape = shape->add_tuple_shapes(); return ShapeUtil::PopulateShape(S32, {}, subshape); }; [](HloInstruction* new_tuple) -> absl::StatusOr<HloInstruction*> { CHECK(new_tuple->shape().IsTuple()); HloInstruction* prefix = nullptr; std::vector<HloInstruction*> users(new_tuple->users()); for (HloInstruction* user : users) { if (user->opcode() == HloOpcode::kGetTupleElement) { continue; } // Lazily extract the prefix on demand, reuse it as needed. if (prefix == nullptr) { prefix = TupleUtil::ExtractPrefix( new_tuple, new_tuple->shape().tuple_shapes_size() - 1); } TF_RETURN_IF_ERROR(new_tuple->ReplaceUseWithDifferentShape(user, prefix)); } return prefix; }; if (VLOG_IS_ON(2)) { VLOG(2) << "Loop condition in " << while_hlo->parent()->name(); VLOG(1) << "loop_bound = " << loop_bound; absl::Status HloControlFlowFlattening::RemoveInfeed( HloInstruction* infeed_hlo) const { CHECK_EQ(infeed_hlo->opcode(), HloOpcode::kInfeed); HloComputation* computation = infeed_hlo->parent(); CHECK_EQ(infeed_hlo->shape().tuple_shapes_size(), 2); const Shape& infeed_shape = ShapeUtil::GetSubshape(infeed_hlo->shape(), {0}); HloInstruction* custom_call = computation->AddInstruction( HloInstruction::CreateCustomCall(infeed_shape, {}, kNopCustomCallTarget)); // Create a new tuple consisting of the constant and the token that was // originally the operand of infeed, and replace the infeed operation. auto new_tuple = HloInstruction::CreateTuple( {custom_call, infeed_hlo->mutable_operand(0)}); TF_RETURN_IF_ERROR( computation->ReplaceWithNewInstruction(infeed_hlo, std::move(new_tuple))); custom_call->SetAndSanitizeName(infeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveRecvAndRecvDone( HloInstruction* recv_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(recv_done->opcode(), HloOpcode::kRecvDone); CHECK_EQ(recv_done->operand_count(), 1); HloInstruction* recv = recv_done->mutable_operand(0); CHECK_EQ(recv->opcode(), HloOpcode::kRecv); HloComputation* computation = recv_done->parent(); CHECK_EQ(recv_done->shape().tuple_shapes_size(), 2); HloModule* module = computation->parent(); HloInstruction* custom_call_recv = computation->AddInstruction(HloInstruction::CreateCustomCall( recv->shape(), recv->operands(), kNopCustomCallTarget)); std::string original_recv_name(recv->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv, custom_call_recv); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(recv, custom_call_recv)); custom_call_recv->SetAndSanitizeName(original_recv_name); std::string original_recv_done_name(recv_done->name()); HloInstruction* custom_call_recv_done = computation->AddInstruction( HloInstruction::CreateCustomCall( recv_done->shape(), recv_done->operands(), kNopCustomCallTarget), recv_done->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, recv_done, custom_call_recv_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(recv_done, custom_call_recv_done)); custom_call_recv_done->SetAndSanitizeName(original_recv_done_name); return std::make_pair(custom_call_recv, custom_call_recv_done); } absl::Status HloControlFlowFlattening::RemoveOutfeed( HloInstruction* outfeed_hlo) const { CHECK_EQ(outfeed_hlo->opcode(), HloOpcode::kOutfeed); HloComputation* computation = outfeed_hlo->parent(); // Replace the outfeed with a no-op custom call with side effect to ensure the // operands aren't DCE'd. HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( outfeed_hlo->shape(), outfeed_hlo->operands(), kNopReturnTokenCustomCallTarget)); Cast<HloCustomCallInstruction>(custom_call) ->set_custom_call_has_side_effect(true); // For SPMD graphs, partitioner requires that side-effecting custom calls have // a sharding that is non-replicated. custom_call->set_sharding(HloSharding::Manual()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(outfeed_hlo, custom_call)); custom_call->SetAndSanitizeName(outfeed_hlo->name()); return absl::OkStatus(); } HloControlFlowFlattening::RemoveSendAndSendDone( HloInstruction* send_done, absl::flat_hash_set<HloInstruction*>* additional_removed) const { CHECK_EQ(send_done->opcode(), HloOpcode::kSendDone); CHECK_EQ(send_done->operand_count(), 1); HloInstruction* send = send_done->mutable_operand(0); CHECK_EQ(send->opcode(), HloOpcode::kSend); HloComputation* computation = send_done->parent(); HloModule* module = computation->parent(); HloInstruction* custom_call_send = computation->AddInstruction(HloInstruction::CreateCustomCall( send->shape(), send->operands(), kNopCustomCallTarget)); std::string original_send_name(send->name()); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send, custom_call_send); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(send, custom_call_send)); custom_call_send->SetAndSanitizeName(original_send_name); HloInstruction* custom_call_send_done = computation->AddInstruction(HloInstruction::CreateCustomCall( send_done->shape(), send_done->operands(), kNopReturnTokenCustomCallTarget)); std::string original_send_done_name(send_done->name()); Cast<HloCustomCallInstruction>(custom_call_send_done) ->set_custom_call_has_side_effect(true); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, send_done, custom_call_send_done); } TF_RETURN_IF_ERROR( computation->ReplaceInstruction(send_done, custom_call_send_done)); custom_call_send_done->SetAndSanitizeName(original_send_done_name); return std::make_pair(custom_call_send, custom_call_send_done); } absl::StatusOr<HloInstruction*> HloControlFlowFlattening::RemoveCollective( HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* custom_call = computation->AddInstruction(HloInstruction::CreateCustomCall( hlo->shape(), hlo->operands(), kNopCustomCallTarget)); // Copy backend config. This is necessary for a collective op in megacore // fusion. custom_call->CopyBackendConfigFrom(hlo); HloModule* module = computation->parent(); if (module->has_schedule() && module->schedule().is_computation_scheduled(computation)) { module->schedule().replace_instruction(computation, hlo, custom_call); } std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, custom_call)); custom_call->SetAndSanitizeName(original_op_name); return custom_call; } absl::Status HloControlFlowFlattening::RemoveId(HloInstruction* hlo) const { HloComputation* computation = hlo->parent(); HloInstruction* zero = CreateConstant(hlo->shape(), computation); std::string original_op_name(hlo->name()); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(hlo, zero)); zero->SetAndSanitizeName(original_op_name); return absl::OkStatus(); } absl::StatusOr<bool> HloControlFlowFlattening::Run( HloModule* module, const absl::flat_hash_set<absl::string_view>& execution_threads) { auto call_graph = CallGraph::Build(module); bool changed = false; absl::flat_hash_set<HloInstruction*> removed; for (HloComputation* computation : module->computations(execution_threads)) { // Do not change computations that are wrapped by async calls. Instead we // remove the async callers if needed. if (computation->IsAsyncComputation()) { continue; } for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { if (removed.contains(instruction)) { // Skip the instruction if it is already removed. continue; } if (flatten_while_loop_ && instruction->opcode() == HloOpcode::kWhile) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(FlattenWhileLoop(instruction, *call_graph)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kInfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveInfeed(instruction)); changed = true; } else if (remove_infeed_outfeed_ && instruction->opcode() == HloOpcode::kOutfeed) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveOutfeed(instruction)); changed = true; } else if (instruction->opcode() == HloOpcode::kSendDone) { auto send_done_instruction = DynCast<HloSendDoneInstruction>(instruction); CHECK(send_done_instruction); if (remove_comm_ || (remove_host_transfer_ && send_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveSendAndSendDone(instruction, &removed).status()); changed = true; } } else if (instruction->opcode() == HloOpcode::kRecvDone) { auto recv_done_instruction = DynCast<HloRecvDoneInstruction>(instruction); CHECK(recv_done_instruction); if (remove_comm_ || (remove_host_transfer_ && recv_done_instruction->is_host_transfer())) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR( RemoveRecvAndRecvDone(instruction, &removed).status()); changed = true; } } else if (remove_comm_ && IsCollective(instruction) && !instruction->parent()->IsFusionComputation() && (instruction->opcode() != HloOpcode::kAsyncStart && instruction->opcode() != HloOpcode::kAsyncUpdate)) { // We do not remove kAsyncStart or kAsyncUpdate here since we expect // them to be removed as a part of the async chain above. // We should remove the async chain all together because the async // wrapped computation is only associated with the AsyncStart. So we // need to refer to the AsyncStart in order to determine whether // the Done or the Update wraps a collective. if (instruction->opcode() == HloOpcode::kAsyncDone) { while (instruction->opcode() == HloOpcode::kAsyncDone || instruction->opcode() == HloOpcode::kAsyncUpdate || instruction->opcode() == HloOpcode::kAsyncStart) { HloInstruction* operand = instruction->mutable_operand(0); VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); instruction = operand; } } else { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveCollective(instruction).status()); } changed = true; } else if (remove_comm_ && (instruction->opcode() == HloOpcode::kPartitionId || instruction->opcode() == HloOpcode::kReplicaId || (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == "SliceId"))) { VLOG(1) << "Remove " << instruction->name(); TF_RETURN_IF_ERROR(RemoveId(instruction)); changed = true; } } } HloDCE hlo_dce; TF_ASSIGN_OR_RETURN(bool dce_changed, hlo_dce.Run(module, execution_threads)); changed |= dce_changed; // Fix the schedule if the module was scheduled. if (changed && module->has_schedule()) { TF_RETURN_IF_ERROR(module->schedule().Update()); } XLA_VLOG_LINES(3, module->ToString()); return changed; } VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); VLOG(1) << "Remove " << instruction->name(); XLA_VLOG_LINES(3, module->ToString());
#include "xla/tools/hlo_control_flow_flattening.h" #include <memory> #include <utility> #include "absl/strings/str_replace.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/service/collective_ops_utils.h" #include "xla/service/despecializer.h" #include "xla/service/hlo_verifier.h" #include "xla/service/spmd/spmd_partitioner.h" #include "xla/tests/hlo_test_base.h" #include "tsl/lib/core/status_test_util.h" class HloControlFlowFlatteningTest : public HloTestBase { public: absl::StatusOr<std::unique_ptr<HloModule>> PartitionComputation( std::unique_ptr<VerifiedHloModule> hlo_module, int64_t num_devices = 2) { spmd::SpmdPartitionerOptions options; auto collective_ops_creator = spmd::GetDefaultCollectiveOpsCreator(num_devices, /*num_replicas=*/1); collective_ops_creator.create_cross_partition_all_gather = nullptr; HloModuleConfig config = GetModuleConfigForTest(); config.set_use_spmd_partitioning(true); config.set_num_partitions(num_devices); HloPassPipeline pass("spmd-partitioning"); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); pass.AddPass<spmd::SpmdPartitioner>(num_devices, /*num_replicas=*/1, options, collective_ops_creator); pass.AddPass<HloVerifier>(/*layout_sensitive=*/false, /*allow_mixed_precision=*/false); TF_RETURN_IF_ERROR(pass.Run(hlo_module.get()).status()); return absl::StatusOr<std::unique_ptr<HloModule>>(std::move(hlo_module)); } }; TEST_F(HloControlFlowFlatteningTest, WhileUser) { absl::string_view hlo_string = R"( HloModule While While.body { loop_var.1 = (s32[], s32[3]{0}) parameter(0) get-tuple-element.1 = s32[] get-tuple-element(loop_var.1), index=0 constant.1 = s32[] constant(1) add = s32[] add(get-tuple-element.1, constant.1) get-tuple-element.2 = s32[3]{0} get-tuple-element(loop_var.1), index=1 multiply = s32[3]{0} multiply(get-tuple-element.2, get-tuple-element.2) ROOT tuple = (s32[], s32[3]{0}) tuple(add, multiply) } While.condition { loop_var.2 = (s32[], s32[3]{0}) parameter(0) get-tuple-element.3 = s32[] get-tuple-element(loop_var.2), index=0 constant.2 = s32[] constant(100) ROOT less-than = pred[] compare(get-tuple-element.3, constant.2), direction=LT } FusedComputation { param = (s32[], s32[3]{0}) parameter(0) get-tuple-element.4 = s32[] get-tuple-element(param), index=0 get-tuple-element.5 = s32[3]{0} get-tuple-element(param), index=1 broadcast = s32[3]{0} broadcast(get-tuple-element.4), dimensions={} ROOT add = s32[3]{0} add(broadcast, get-tuple-element.5) } ENTRY While { constant.3 = s32[] constant(42) constant.4 = s32[3]{0} constant({0, 1, 2}) tuple.1 = (s32[], s32[3]{0}) tuple(constant.3, constant.4) while = (s32[], s32[3]{0}) while(tuple.1), condition=While.condition, body=While.body ROOT fusion = s32[3]{0} fusion(while), kind=kLoop, calls=FusedComputation } )"; TF_ASSERT_OK_AND_ASSIGN(auto module, ParseAndReturnVerifiedModule(hlo_string)); HloControlFlowFlattening flattening( HloControlFlowFlattening::Options{/*while_execution_count=*/3}); EXPECT_TRUE(flattening.Run(module.get()).value()); TF_ASSERT_OK(HloVerifier(/*layout_sensitive=*/true, /*allow_mixed_precision=*/true) .Run(module.get()) .status()); auto fusion = module->entry_computation()->root_instruction(); auto while_op = module->entry_computation()->GetInstructionWithName("while"); EXPECT_THAT(fusion, op::Fusion(op::Tuple(op::GetTupleElement(while_op, 0), op::GetTupleElement(while_op, 1)))); }
HloExtractorTest_ExtractDag
xla/tools/hlo_extractor_test.cc
explicit ExtractionVisitor( const HloInstruction* root_instruction, absl::flat_hash_set<const HloInstruction*>* boundary, ExtractSelector extract_selector, ReplaceTypeSelector replace_type_selector) : root_instruction_(root_instruction), old_module_(root_instruction->GetModule()), module_(std::make_unique<HloModule>( "extracted", config_, std::make_unique<CompilationEnvironments>( old_module_->comp_envs()))), clone_context_(module_.get()), boundary_(boundary), extract_selector_(extract_selector), replace_type_selector_(replace_type_selector) { // Initialize the computation builder for every computations. for (auto computation : old_module_->computations()) { old_computations_to_builders_.insert( {computation, std::make_unique<HloComputation::Builder>(computation->name())}); } // Initialize the parameter counter for every computations. for (auto computation : old_module_->computations()) { parameter_numbers_[computation] = 0; } } absl::Status HandleParameter(const HloInstruction* parameter) override { // Entry parameters need renumbering. return ReplaceWithParameter(parameter); } absl::Status DefaultAction(const HloInstruction* hlo) override { // Replace the following two types of instructions with parameters/constants // (1) the instructions at the boundary with (2) the instructions that are // not selected by the hlo_selector. if ((boundary_ != nullptr && boundary_->contains(hlo) > 0) || (extract_selector_ != nullptr && !extract_selector_(hlo))) { if (replace_type_selector_ != nullptr) { switch (replace_type_selector_(hlo)) { case ReplaceType::kReplaceConst: return ReplaceWithConstant(hlo); case ReplaceType::kReplaceParam: CHECK(hlo->parent() == root_instruction_->parent()) << "Replacing instructions at non-entry computation with " "parameters is not supported."; return ReplaceWithParameter(hlo); case ReplaceType::kReplaceZeroBroadcast: return ReplaceWithConstantBroadcast( hlo, ReplaceType::kReplaceZeroBroadcast); case ReplaceType::kReplaceRandomBroadcast: return ReplaceWithConstantBroadcast( hlo, ReplaceType::kReplaceRandomBroadcast); default: QCHECK(false) << "Unsupported replacement type"; } } return ReplaceWithParameter(hlo); } // Clone the visiting hlo and add it to computation builder. std::vector<HloInstruction*> new_operands; for (auto operand : hlo->operands()) { new_operands.push_back(clone_context_.GetInstruction(operand)); } auto instruction = hlo->CloneWithNewOperands(hlo->shape(), new_operands, &clone_context_); auto it = old_computations_to_builders_.find(hlo->parent()); CHECK(it != old_computations_to_builders_.end()); auto builder = it->second.get(); builder->AddInstruction(std::move(instruction)); // If the visiting `hlo` is the root instruction of a computation (except // for the root of the entry computation), we can build the new computation // now and put it in `clone_context_`. The entry computation would be built // in `FinishVisit()` when all the instructions are visited. if (hlo->IsRoot() && hlo != root_instruction_) { CHECK(clone_context_.FindComputation(hlo->parent()) == nullptr); auto new_computation = module_->AddEmbeddedComputation(builder->Build()); clone_context_.MapComputation(hlo->parent(), new_computation); } return absl::OkStatus(); } absl::Status FinishVisit(const HloInstruction* /*root*/) override { // Create the entry computation for the extracted module. auto new_entry_computation = module_->AddEntryComputation( old_computations_to_builders_.at(root_instruction_->parent())->Build()); clone_context_.MapComputation(root_instruction_->parent(), new_entry_computation); // Rename HLOs so that their name matches the original. By default, // HLOs get new unique names when adding a new entry computation to // a module. for (auto computation : old_module_->MakeComputationPostOrder()) { for (auto old_instruction : computation->MakeInstructionPostOrder()) { if (auto new_instruction = clone_context_.FindInstruction(old_instruction)) { new_instruction->SetAndSanitizeName(old_instruction->name()); } } } // For the extra created instructions (e.g., the ones created when replacing // with broadcasted zeros), we make sure they have unique names without // breaking the matches made at above code. for (HloInstruction* instruction : extra_created_instructions_) { module_->SetAndUniquifyInstrName(instruction, instruction->name()); } return absl::OkStatus(); } absl::Status ReplaceWithConstant(const HloInstruction* hlo) { absl::StatusOr<Literal> literal_status = MakeFakeLiteral(hlo->shape()); TF_CHECK_OK(literal_status.status()); auto new_const = HloInstruction::CreateConstant(std::move(literal_status.value())); clone_context_.MapInstruction(hlo, new_const.get()); auto it = old_computations_to_builders_.find(hlo->parent()); CHECK(it != old_computations_to_builders_.end()); auto builder = it->second.get(); builder->AddInstruction(std::move(new_const)); return absl::OkStatus(); } absl::Status ReplaceWithParameter(const HloInstruction* hlo) { CHECK(parameter_numbers_.contains(hlo->parent())); auto new_parameter = HloInstruction::CreateParameter( parameter_numbers_.at(hlo->parent())++, hlo->shape(), hlo->name()); clone_context_.MapInstruction(hlo, new_parameter.get()); CHECK(old_computations_to_builders_.contains(hlo->parent())); auto builder = old_computations_to_builders_[hlo->parent()].get(); builder->AddInstruction(std::move(new_parameter)); return absl::OkStatus(); } HloInstruction* ReplaceWithConstantBroadcastHelper( const Shape& shape, HloComputation::Builder* builder, ReplaceType replace_type) { if (shape.IsTuple()) { // If it is a tuple, recursively create a zero instruction. std::vector<HloInstruction*> tuple_operands; for (const auto& subshape : shape.tuple_shapes()) { tuple_operands.push_back(ReplaceWithConstantBroadcastHelper( subshape, builder, replace_type)); } auto zero_tuple = builder->AddInstruction(HloInstruction::CreateTuple(tuple_operands)); extra_created_instructions_.push_back(zero_tuple); return zero_tuple; } else { // If not a tuple, we need to create a zero constant of // `shape.element_type()`, and then broadcast it into the shape we want. // Create a constant of `shape.element_type()`. The constant could be // either a zero or a random number, depending on `replace_type`. Shape constant_shape = ShapeUtil::MakeShape(shape.element_type(), {}); HloInstruction* constant_instruction; CHECK(replace_type == ReplaceType::kReplaceZeroBroadcast || replace_type == ReplaceType::kReplaceRandomBroadcast); if (replace_type == ReplaceType::kReplaceZeroBroadcast) { constant_instruction = builder->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(constant_shape.element_type()))); } else { absl::StatusOr<Literal> literal_status = MakeFakeLiteral(constant_shape); TF_CHECK_OK(literal_status.status()); constant_instruction = builder->AddInstruction( HloInstruction::CreateConstant(std::move(literal_status.value()))); } extra_created_instructions_.push_back(constant_instruction); // Broadcast `constant_instruction` to create an hlo of the desired // shape. auto broadcast_constant_instruction = builder->AddInstruction( HloInstruction::CreateBroadcast(shape, constant_instruction, {})); extra_created_instructions_.push_back(broadcast_constant_instruction); return broadcast_constant_instruction; } } absl::Status ReplaceWithConstantBroadcast(const HloInstruction* hlo, ReplaceType replace_type) { CHECK(replace_type == ReplaceType::kReplaceZeroBroadcast || replace_type == ReplaceType::kReplaceRandomBroadcast); CHECK(old_computations_to_builders_.contains(hlo->parent())); auto builder = old_computations_to_builders_[hlo->parent()].get(); HloInstruction* zero_broadcast = ReplaceWithConstantBroadcastHelper(hlo->shape(), builder, replace_type); clone_context_.MapInstruction(hlo, zero_broadcast); return absl::OkStatus(); } void ComputeBoundary(const HloInstruction* root, int64_t limit, absl::flat_hash_set<const HloInstruction*>* boundary) { std::deque<const HloInstruction*> worklist; absl::flat_hash_map<const HloInstruction*, int64_t> visited; worklist.push_back(root); visited.emplace(root, 0); while (!worklist.empty()) { auto hlo = worklist.front(); worklist.pop_front(); int64_t hops = visited[hlo]; if (hops > limit) { boundary->insert(hlo); continue; } for (const HloInstruction* operand : hlo->operands()) { if (visited.count(operand)) { continue; } worklist.push_back(operand); visited.emplace(operand, hops + 1); } } } std::unique_ptr<HloModule> ExtractModule( const HloInstruction* instruction, int64_t height, ExtractSelector extract_selector, ReplaceTypeSelector replace_type_selector, bool cross_computation) { QCHECK(height == -1 || !cross_computation) << "Boundary cannnot be calculated across the computations."; absl::flat_hash_set<const HloInstruction*> boundary; if (height != -1) { ComputeBoundary(instruction, height, &boundary); } ExtractionVisitor visitor(instruction, &boundary, extract_selector, replace_type_selector); TF_CHECK_OK(instruction->Accept(&visitor, /*call_finish_visit=*/true, /*ignore_control_predecessors=*/false, /*cross_computation=*/cross_computation)); // The first pass may leave unused parameter instructions in the entry // computation. Do another extraction pass to remove unused parameters in the // entry computation. This is done because HloComputation does not allow // removing parameters after the computation has been built. ExtractionVisitor cleanup_visitor( visitor.module()->entry_computation()->root_instruction(), /*boundary=*/nullptr, /*extract_selector=*/nullptr, /*replace_type_selector=*/nullptr); TF_CHECK_OK(visitor.module()->entry_computation()->root_instruction()->Accept( &cleanup_visitor, /*call_finish_visit=*/true, /*ignore_control_predecessors=*/false, /*cross_computation=*/false)); HloVerifier verifier(/*layout_sensitive=*/false, /*allow_mixed_precision=*/true); TF_CHECK_OK(verifier.Run(cleanup_visitor.module()).status()); return cleanup_visitor.ConsumeModule(); }
#include "xla/tools/hlo_extractor.h" #include <memory> #include <string> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/tests/hlo_test_base.h" #include "tsl/platform/statusor.h" TEST_F(HloExtractorTest, ExtractDag) { const std::string& hlo_string = R"( HloModule test ENTRY %entry { param.0 = f32[4]{0} parameter(0) tanh = f32[4]{0} tanh(f32[4]{0} param.0) negate = f32[4]{0} negate(f32[4]{0} tanh) exp = f32[4]{0} exponential(f32[4]{0} negate) ROOT add = f32[4]{0} add(f32[4]{0} negate, f32[4]{0} exp) } )"; TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> hlo_module, ParseAndReturnVerifiedModule(hlo_string)); { auto extracted_module = ExtractModule(FindInstruction(hlo_module.get(), "exp")); EXPECT_THAT(extracted_module->entry_computation()->root_instruction(), op::Exp(op::Negate(op::Tanh(op::Parameter(0))))); } { auto extracted_module = ExtractModule(FindInstruction(hlo_module.get(), "add"), /*height=*/0); EXPECT_THAT(extracted_module->entry_computation()->root_instruction(), op::Add(op::Parameter(0), op::Parameter(1))); } { auto extracted_module = ExtractModule(FindInstruction(hlo_module.get(), "add"), /*height=*/1); EXPECT_THAT(extracted_module->entry_computation()->root_instruction(), op::Add(op::Negate(op::Parameter(0)), op::Exp(op::Negate(op::Parameter(0))))); } { auto extracted_module = ExtractModule(FindInstruction(hlo_module.get(), "add"), /*height=*/2); EXPECT_THAT(extracted_module->entry_computation()->root_instruction(), op::Add(op::Negate(op::Tanh(op::Parameter(0))), op::Exp(op::Negate(op::Tanh(op::Parameter(0)))))); } }
HloExtractorTest_ExtractFromMultipleComputation
xla/tools/hlo_extractor_test.cc
explicit ExtractionVisitor( const HloInstruction* root_instruction, absl::flat_hash_set<const HloInstruction*>* boundary, ExtractSelector extract_selector, ReplaceTypeSelector replace_type_selector) : root_instruction_(root_instruction), old_module_(root_instruction->GetModule()), module_(std::make_unique<HloModule>( "extracted", config_, std::make_unique<CompilationEnvironments>( old_module_->comp_envs()))), clone_context_(module_.get()), boundary_(boundary), extract_selector_(extract_selector), replace_type_selector_(replace_type_selector) { // Initialize the computation builder for every computations. for (auto computation : old_module_->computations()) { old_computations_to_builders_.insert( {computation, std::make_unique<HloComputation::Builder>(computation->name())}); } // Initialize the parameter counter for every computations. for (auto computation : old_module_->computations()) { parameter_numbers_[computation] = 0; } } absl::Status HandleParameter(const HloInstruction* parameter) override { // Entry parameters need renumbering. return ReplaceWithParameter(parameter); } absl::Status DefaultAction(const HloInstruction* hlo) override { // Replace the following two types of instructions with parameters/constants // (1) the instructions at the boundary with (2) the instructions that are // not selected by the hlo_selector. if ((boundary_ != nullptr && boundary_->contains(hlo) > 0) || (extract_selector_ != nullptr && !extract_selector_(hlo))) { if (replace_type_selector_ != nullptr) { switch (replace_type_selector_(hlo)) { case ReplaceType::kReplaceConst: return ReplaceWithConstant(hlo); case ReplaceType::kReplaceParam: CHECK(hlo->parent() == root_instruction_->parent()) << "Replacing instructions at non-entry computation with " "parameters is not supported."; return ReplaceWithParameter(hlo); case ReplaceType::kReplaceZeroBroadcast: return ReplaceWithConstantBroadcast( hlo, ReplaceType::kReplaceZeroBroadcast); case ReplaceType::kReplaceRandomBroadcast: return ReplaceWithConstantBroadcast( hlo, ReplaceType::kReplaceRandomBroadcast); default: QCHECK(false) << "Unsupported replacement type"; } } return ReplaceWithParameter(hlo); } // Clone the visiting hlo and add it to computation builder. std::vector<HloInstruction*> new_operands; for (auto operand : hlo->operands()) { new_operands.push_back(clone_context_.GetInstruction(operand)); } auto instruction = hlo->CloneWithNewOperands(hlo->shape(), new_operands, &clone_context_); auto it = old_computations_to_builders_.find(hlo->parent()); CHECK(it != old_computations_to_builders_.end()); auto builder = it->second.get(); builder->AddInstruction(std::move(instruction)); // If the visiting `hlo` is the root instruction of a computation (except // for the root of the entry computation), we can build the new computation // now and put it in `clone_context_`. The entry computation would be built // in `FinishVisit()` when all the instructions are visited. if (hlo->IsRoot() && hlo != root_instruction_) { CHECK(clone_context_.FindComputation(hlo->parent()) == nullptr); auto new_computation = module_->AddEmbeddedComputation(builder->Build()); clone_context_.MapComputation(hlo->parent(), new_computation); } return absl::OkStatus(); } absl::Status FinishVisit(const HloInstruction* /*root*/) override { // Create the entry computation for the extracted module. auto new_entry_computation = module_->AddEntryComputation( old_computations_to_builders_.at(root_instruction_->parent())->Build()); clone_context_.MapComputation(root_instruction_->parent(), new_entry_computation); // Rename HLOs so that their name matches the original. By default, // HLOs get new unique names when adding a new entry computation to // a module. for (auto computation : old_module_->MakeComputationPostOrder()) { for (auto old_instruction : computation->MakeInstructionPostOrder()) { if (auto new_instruction = clone_context_.FindInstruction(old_instruction)) { new_instruction->SetAndSanitizeName(old_instruction->name()); } } } // For the extra created instructions (e.g., the ones created when replacing // with broadcasted zeros), we make sure they have unique names without // breaking the matches made at above code. for (HloInstruction* instruction : extra_created_instructions_) { module_->SetAndUniquifyInstrName(instruction, instruction->name()); } return absl::OkStatus(); } absl::Status ReplaceWithConstant(const HloInstruction* hlo) { absl::StatusOr<Literal> literal_status = MakeFakeLiteral(hlo->shape()); TF_CHECK_OK(literal_status.status()); auto new_const = HloInstruction::CreateConstant(std::move(literal_status.value())); clone_context_.MapInstruction(hlo, new_const.get()); auto it = old_computations_to_builders_.find(hlo->parent()); CHECK(it != old_computations_to_builders_.end()); auto builder = it->second.get(); builder->AddInstruction(std::move(new_const)); return absl::OkStatus(); } absl::Status ReplaceWithParameter(const HloInstruction* hlo) { CHECK(parameter_numbers_.contains(hlo->parent())); auto new_parameter = HloInstruction::CreateParameter( parameter_numbers_.at(hlo->parent())++, hlo->shape(), hlo->name()); clone_context_.MapInstruction(hlo, new_parameter.get()); CHECK(old_computations_to_builders_.contains(hlo->parent())); auto builder = old_computations_to_builders_[hlo->parent()].get(); builder->AddInstruction(std::move(new_parameter)); return absl::OkStatus(); } HloInstruction* ReplaceWithConstantBroadcastHelper( const Shape& shape, HloComputation::Builder* builder, ReplaceType replace_type) { if (shape.IsTuple()) { // If it is a tuple, recursively create a zero instruction. std::vector<HloInstruction*> tuple_operands; for (const auto& subshape : shape.tuple_shapes()) { tuple_operands.push_back(ReplaceWithConstantBroadcastHelper( subshape, builder, replace_type)); } auto zero_tuple = builder->AddInstruction(HloInstruction::CreateTuple(tuple_operands)); extra_created_instructions_.push_back(zero_tuple); return zero_tuple; } else { // If not a tuple, we need to create a zero constant of // `shape.element_type()`, and then broadcast it into the shape we want. // Create a constant of `shape.element_type()`. The constant could be // either a zero or a random number, depending on `replace_type`. Shape constant_shape = ShapeUtil::MakeShape(shape.element_type(), {}); HloInstruction* constant_instruction; CHECK(replace_type == ReplaceType::kReplaceZeroBroadcast || replace_type == ReplaceType::kReplaceRandomBroadcast); if (replace_type == ReplaceType::kReplaceZeroBroadcast) { constant_instruction = builder->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(constant_shape.element_type()))); } else { absl::StatusOr<Literal> literal_status = MakeFakeLiteral(constant_shape); TF_CHECK_OK(literal_status.status()); constant_instruction = builder->AddInstruction( HloInstruction::CreateConstant(std::move(literal_status.value()))); } extra_created_instructions_.push_back(constant_instruction); // Broadcast `constant_instruction` to create an hlo of the desired // shape. auto broadcast_constant_instruction = builder->AddInstruction( HloInstruction::CreateBroadcast(shape, constant_instruction, {})); extra_created_instructions_.push_back(broadcast_constant_instruction); return broadcast_constant_instruction; } } absl::Status ReplaceWithConstantBroadcast(const HloInstruction* hlo, ReplaceType replace_type) { CHECK(replace_type == ReplaceType::kReplaceZeroBroadcast || replace_type == ReplaceType::kReplaceRandomBroadcast); CHECK(old_computations_to_builders_.contains(hlo->parent())); auto builder = old_computations_to_builders_[hlo->parent()].get(); HloInstruction* zero_broadcast = ReplaceWithConstantBroadcastHelper(hlo->shape(), builder, replace_type); clone_context_.MapInstruction(hlo, zero_broadcast); return absl::OkStatus(); } void ComputeBoundary(const HloInstruction* root, int64_t limit, absl::flat_hash_set<const HloInstruction*>* boundary) { std::deque<const HloInstruction*> worklist; absl::flat_hash_map<const HloInstruction*, int64_t> visited; worklist.push_back(root); visited.emplace(root, 0); while (!worklist.empty()) { auto hlo = worklist.front(); worklist.pop_front(); int64_t hops = visited[hlo]; if (hops > limit) { boundary->insert(hlo); continue; } for (const HloInstruction* operand : hlo->operands()) { if (visited.count(operand)) { continue; } worklist.push_back(operand); visited.emplace(operand, hops + 1); } } } std::unique_ptr<HloModule> ExtractModule( const HloInstruction* instruction, int64_t height, ExtractSelector extract_selector, ReplaceTypeSelector replace_type_selector, bool cross_computation) { QCHECK(height == -1 || !cross_computation) << "Boundary cannnot be calculated across the computations."; absl::flat_hash_set<const HloInstruction*> boundary; if (height != -1) { ComputeBoundary(instruction, height, &boundary); } ExtractionVisitor visitor(instruction, &boundary, extract_selector, replace_type_selector); TF_CHECK_OK(instruction->Accept(&visitor, /*call_finish_visit=*/true, /*ignore_control_predecessors=*/false, /*cross_computation=*/cross_computation)); // The first pass may leave unused parameter instructions in the entry // computation. Do another extraction pass to remove unused parameters in the // entry computation. This is done because HloComputation does not allow // removing parameters after the computation has been built. ExtractionVisitor cleanup_visitor( visitor.module()->entry_computation()->root_instruction(), /*boundary=*/nullptr, /*extract_selector=*/nullptr, /*replace_type_selector=*/nullptr); TF_CHECK_OK(visitor.module()->entry_computation()->root_instruction()->Accept( &cleanup_visitor, /*call_finish_visit=*/true, /*ignore_control_predecessors=*/false, /*cross_computation=*/false)); HloVerifier verifier(/*layout_sensitive=*/false, /*allow_mixed_precision=*/true); TF_CHECK_OK(verifier.Run(cleanup_visitor.module()).status()); return cleanup_visitor.ConsumeModule(); }
#include "xla/tools/hlo_extractor.h" #include <memory> #include <string> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/tests/hlo_test_base.h" #include "tsl/platform/statusor.h" TEST_F(HloExtractorTest, ExtractFromMultipleComputation) { const std::string& hlo_string = R"( HloModule axpy_module calculate_alpha { c.1 = f32[] constant(1) c.2 = f32[] constant(2) add.0 = f32[] add(c.1, c.2) c.3 = f32[] constant(4) ROOT ret = f32[] subtract(add.0, c.3) } ENTRY axpy_computation { alpha = f32[] call(), to_apply=calculate_alpha broadcast = f32[10] broadcast(alpha), dimensions={} x = f32[10] parameter(0) ax = f32[10] multiply(broadcast, x) y = f32[10] parameter(1) ROOT add.1 = f32[10] add(ax, y) } )"; TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> hlo_module, ParseAndReturnVerifiedModule(hlo_string)); HloInstruction* inst = FindInstruction(hlo_module.get(), "add.0"); EXPECT_THAT(inst, op::Add()); auto extract_selector = [&inst](const HloInstruction* hlo_inst) { return hlo_inst != inst; }; // Exclude `add.0 = f32[] add(c.1, c.2)` from computation `calculate_alpha`, // and replace it with a constant. { auto replace_type_selector = [](const HloInstruction* hlo_inst) { return ReplaceType::kReplaceConst; }; auto extracted_module = ExtractModule(hlo_module->entry_computation()->root_instruction(), /*height=*/-1, /*extract_selector=*/extract_selector, /*replace_type_selector=*/replace_type_selector, /*cross_computation=*/true); EXPECT_EQ(extracted_module->computation_count(), 2); auto calculate_alpha_root_instruction = FindComputation(extracted_module.get(), "calculate_alpha") ->root_instruction(); EXPECT_THAT(calculate_alpha_root_instruction, op::Subtract(op::Constant(), op::Constant())); } // Exclude `add.0 = f32[] add(c.1, c.2)` from computation `calculate_alpha`, // and replace it with a broadcasted zero. { auto replace_type_selector = [](const HloInstruction* hlo_inst) { return ReplaceType::kReplaceZeroBroadcast; }; auto extracted_module = ExtractModule(hlo_module->entry_computation()->root_instruction(), /*height=*/-1, /*extract_selector=*/extract_selector, /*replace_type_selector=*/replace_type_selector, /*cross_computation=*/true); EXPECT_EQ(extracted_module->computation_count(), 2); auto calculate_alpha_root_instruction = FindComputation(extracted_module.get(), "calculate_alpha") ->root_instruction(); EXPECT_THAT(calculate_alpha_root_instruction, op::Subtract(op::Broadcast(op::Constant()), op::Constant())); } }
HloExtractorTest_ExtractTopLevel
xla/tools/hlo_extractor_test.cc
explicit ExtractionVisitor( const HloInstruction* root_instruction, absl::flat_hash_set<const HloInstruction*>* boundary, ExtractSelector extract_selector, ReplaceTypeSelector replace_type_selector) : root_instruction_(root_instruction), old_module_(root_instruction->GetModule()), module_(std::make_unique<HloModule>( "extracted", config_, std::make_unique<CompilationEnvironments>( old_module_->comp_envs()))), clone_context_(module_.get()), boundary_(boundary), extract_selector_(extract_selector), replace_type_selector_(replace_type_selector) { // Initialize the computation builder for every computations. for (auto computation : old_module_->computations()) { old_computations_to_builders_.insert( {computation, std::make_unique<HloComputation::Builder>(computation->name())}); } // Initialize the parameter counter for every computations. for (auto computation : old_module_->computations()) { parameter_numbers_[computation] = 0; } } absl::Status HandleParameter(const HloInstruction* parameter) override { // Entry parameters need renumbering. return ReplaceWithParameter(parameter); } absl::Status DefaultAction(const HloInstruction* hlo) override { // Replace the following two types of instructions with parameters/constants // (1) the instructions at the boundary with (2) the instructions that are // not selected by the hlo_selector. if ((boundary_ != nullptr && boundary_->contains(hlo) > 0) || (extract_selector_ != nullptr && !extract_selector_(hlo))) { if (replace_type_selector_ != nullptr) { switch (replace_type_selector_(hlo)) { case ReplaceType::kReplaceConst: return ReplaceWithConstant(hlo); case ReplaceType::kReplaceParam: CHECK(hlo->parent() == root_instruction_->parent()) << "Replacing instructions at non-entry computation with " "parameters is not supported."; return ReplaceWithParameter(hlo); case ReplaceType::kReplaceZeroBroadcast: return ReplaceWithConstantBroadcast( hlo, ReplaceType::kReplaceZeroBroadcast); case ReplaceType::kReplaceRandomBroadcast: return ReplaceWithConstantBroadcast( hlo, ReplaceType::kReplaceRandomBroadcast); default: QCHECK(false) << "Unsupported replacement type"; } } return ReplaceWithParameter(hlo); } // Clone the visiting hlo and add it to computation builder. std::vector<HloInstruction*> new_operands; for (auto operand : hlo->operands()) { new_operands.push_back(clone_context_.GetInstruction(operand)); } auto instruction = hlo->CloneWithNewOperands(hlo->shape(), new_operands, &clone_context_); auto it = old_computations_to_builders_.find(hlo->parent()); CHECK(it != old_computations_to_builders_.end()); auto builder = it->second.get(); builder->AddInstruction(std::move(instruction)); // If the visiting `hlo` is the root instruction of a computation (except // for the root of the entry computation), we can build the new computation // now and put it in `clone_context_`. The entry computation would be built // in `FinishVisit()` when all the instructions are visited. if (hlo->IsRoot() && hlo != root_instruction_) { CHECK(clone_context_.FindComputation(hlo->parent()) == nullptr); auto new_computation = module_->AddEmbeddedComputation(builder->Build()); clone_context_.MapComputation(hlo->parent(), new_computation); } return absl::OkStatus(); } absl::Status FinishVisit(const HloInstruction* /*root*/) override { // Create the entry computation for the extracted module. auto new_entry_computation = module_->AddEntryComputation( old_computations_to_builders_.at(root_instruction_->parent())->Build()); clone_context_.MapComputation(root_instruction_->parent(), new_entry_computation); // Rename HLOs so that their name matches the original. By default, // HLOs get new unique names when adding a new entry computation to // a module. for (auto computation : old_module_->MakeComputationPostOrder()) { for (auto old_instruction : computation->MakeInstructionPostOrder()) { if (auto new_instruction = clone_context_.FindInstruction(old_instruction)) { new_instruction->SetAndSanitizeName(old_instruction->name()); } } } // For the extra created instructions (e.g., the ones created when replacing // with broadcasted zeros), we make sure they have unique names without // breaking the matches made at above code. for (HloInstruction* instruction : extra_created_instructions_) { module_->SetAndUniquifyInstrName(instruction, instruction->name()); } return absl::OkStatus(); } absl::Status ReplaceWithConstant(const HloInstruction* hlo) { absl::StatusOr<Literal> literal_status = MakeFakeLiteral(hlo->shape()); TF_CHECK_OK(literal_status.status()); auto new_const = HloInstruction::CreateConstant(std::move(literal_status.value())); clone_context_.MapInstruction(hlo, new_const.get()); auto it = old_computations_to_builders_.find(hlo->parent()); CHECK(it != old_computations_to_builders_.end()); auto builder = it->second.get(); builder->AddInstruction(std::move(new_const)); return absl::OkStatus(); } absl::Status ReplaceWithParameter(const HloInstruction* hlo) { CHECK(parameter_numbers_.contains(hlo->parent())); auto new_parameter = HloInstruction::CreateParameter( parameter_numbers_.at(hlo->parent())++, hlo->shape(), hlo->name()); clone_context_.MapInstruction(hlo, new_parameter.get()); CHECK(old_computations_to_builders_.contains(hlo->parent())); auto builder = old_computations_to_builders_[hlo->parent()].get(); builder->AddInstruction(std::move(new_parameter)); return absl::OkStatus(); } HloInstruction* ReplaceWithConstantBroadcastHelper( const Shape& shape, HloComputation::Builder* builder, ReplaceType replace_type) { if (shape.IsTuple()) { // If it is a tuple, recursively create a zero instruction. std::vector<HloInstruction*> tuple_operands; for (const auto& subshape : shape.tuple_shapes()) { tuple_operands.push_back(ReplaceWithConstantBroadcastHelper( subshape, builder, replace_type)); } auto zero_tuple = builder->AddInstruction(HloInstruction::CreateTuple(tuple_operands)); extra_created_instructions_.push_back(zero_tuple); return zero_tuple; } else { // If not a tuple, we need to create a zero constant of // `shape.element_type()`, and then broadcast it into the shape we want. // Create a constant of `shape.element_type()`. The constant could be // either a zero or a random number, depending on `replace_type`. Shape constant_shape = ShapeUtil::MakeShape(shape.element_type(), {}); HloInstruction* constant_instruction; CHECK(replace_type == ReplaceType::kReplaceZeroBroadcast || replace_type == ReplaceType::kReplaceRandomBroadcast); if (replace_type == ReplaceType::kReplaceZeroBroadcast) { constant_instruction = builder->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(constant_shape.element_type()))); } else { absl::StatusOr<Literal> literal_status = MakeFakeLiteral(constant_shape); TF_CHECK_OK(literal_status.status()); constant_instruction = builder->AddInstruction( HloInstruction::CreateConstant(std::move(literal_status.value()))); } extra_created_instructions_.push_back(constant_instruction); // Broadcast `constant_instruction` to create an hlo of the desired // shape. auto broadcast_constant_instruction = builder->AddInstruction( HloInstruction::CreateBroadcast(shape, constant_instruction, {})); extra_created_instructions_.push_back(broadcast_constant_instruction); return broadcast_constant_instruction; } } absl::Status ReplaceWithConstantBroadcast(const HloInstruction* hlo, ReplaceType replace_type) { CHECK(replace_type == ReplaceType::kReplaceZeroBroadcast || replace_type == ReplaceType::kReplaceRandomBroadcast); CHECK(old_computations_to_builders_.contains(hlo->parent())); auto builder = old_computations_to_builders_[hlo->parent()].get(); HloInstruction* zero_broadcast = ReplaceWithConstantBroadcastHelper(hlo->shape(), builder, replace_type); clone_context_.MapInstruction(hlo, zero_broadcast); return absl::OkStatus(); } void ComputeBoundary(const HloInstruction* root, int64_t limit, absl::flat_hash_set<const HloInstruction*>* boundary) { std::deque<const HloInstruction*> worklist; absl::flat_hash_map<const HloInstruction*, int64_t> visited; worklist.push_back(root); visited.emplace(root, 0); while (!worklist.empty()) { auto hlo = worklist.front(); worklist.pop_front(); int64_t hops = visited[hlo]; if (hops > limit) { boundary->insert(hlo); continue; } for (const HloInstruction* operand : hlo->operands()) { if (visited.count(operand)) { continue; } worklist.push_back(operand); visited.emplace(operand, hops + 1); } } } std::unique_ptr<HloModule> ExtractModule( const HloInstruction* instruction, int64_t height, ExtractSelector extract_selector, ReplaceTypeSelector replace_type_selector, bool cross_computation) { QCHECK(height == -1 || !cross_computation) << "Boundary cannnot be calculated across the computations."; absl::flat_hash_set<const HloInstruction*> boundary; if (height != -1) { ComputeBoundary(instruction, height, &boundary); } ExtractionVisitor visitor(instruction, &boundary, extract_selector, replace_type_selector); TF_CHECK_OK(instruction->Accept(&visitor, /*call_finish_visit=*/true, /*ignore_control_predecessors=*/false, /*cross_computation=*/cross_computation)); // The first pass may leave unused parameter instructions in the entry // computation. Do another extraction pass to remove unused parameters in the // entry computation. This is done because HloComputation does not allow // removing parameters after the computation has been built. ExtractionVisitor cleanup_visitor( visitor.module()->entry_computation()->root_instruction(), /*boundary=*/nullptr, /*extract_selector=*/nullptr, /*replace_type_selector=*/nullptr); TF_CHECK_OK(visitor.module()->entry_computation()->root_instruction()->Accept( &cleanup_visitor, /*call_finish_visit=*/true, /*ignore_control_predecessors=*/false, /*cross_computation=*/false)); HloVerifier verifier(/*layout_sensitive=*/false, /*allow_mixed_precision=*/true); TF_CHECK_OK(verifier.Run(cleanup_visitor.module()).status()); return cleanup_visitor.ConsumeModule(); }
#include "xla/tools/hlo_extractor.h" #include <memory> #include <string> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/tests/hlo_test_base.h" #include "tsl/platform/statusor.h" TEST_F(HloExtractorTest, ExtractTopLevel) { const std::string& hlo_string = R"( HloModule test ENTRY %entry { param.0 = f32[4]{0} parameter(0) negate = f32[4]{0} negate(f32[4]{0} param.0) ROOT exp = f32[4]{0} exponential(f32[4]{0} negate) } )"; TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> hlo_module, ParseAndReturnVerifiedModule(hlo_string)); { auto extracted_module = ExtractModule(FindInstruction(hlo_module.get(), "exp")); EXPECT_THAT(extracted_module->entry_computation()->root_instruction(), op::Exp(op::Negate(op::Parameter(0)))); } { auto extracted_module = ExtractModule(FindInstruction(hlo_module.get(), "exp"), /*height=*/0); EXPECT_THAT(extracted_module->entry_computation()->root_instruction(), op::Exp(op::Parameter(0))); } { auto extracted_module = ExtractModule( FindInstruction(hlo_module.get(), "negate"), /*height=*/0); EXPECT_THAT(extracted_module->entry_computation()->root_instruction(), op::Negate(op::Parameter(0))); } }
HloExtractorTest_ExtractWithConstant
xla/tools/hlo_extractor_test.cc
explicit ExtractionVisitor( const HloInstruction* root_instruction, absl::flat_hash_set<const HloInstruction*>* boundary, ExtractSelector extract_selector, ReplaceTypeSelector replace_type_selector) : root_instruction_(root_instruction), old_module_(root_instruction->GetModule()), module_(std::make_unique<HloModule>( "extracted", config_, std::make_unique<CompilationEnvironments>( old_module_->comp_envs()))), clone_context_(module_.get()), boundary_(boundary), extract_selector_(extract_selector), replace_type_selector_(replace_type_selector) { // Initialize the computation builder for every computations. for (auto computation : old_module_->computations()) { old_computations_to_builders_.insert( {computation, std::make_unique<HloComputation::Builder>(computation->name())}); } // Initialize the parameter counter for every computations. for (auto computation : old_module_->computations()) { parameter_numbers_[computation] = 0; } } absl::Status HandleParameter(const HloInstruction* parameter) override { // Entry parameters need renumbering. return ReplaceWithParameter(parameter); } absl::Status DefaultAction(const HloInstruction* hlo) override { // Replace the following two types of instructions with parameters/constants // (1) the instructions at the boundary with (2) the instructions that are // not selected by the hlo_selector. if ((boundary_ != nullptr && boundary_->contains(hlo) > 0) || (extract_selector_ != nullptr && !extract_selector_(hlo))) { if (replace_type_selector_ != nullptr) { switch (replace_type_selector_(hlo)) { case ReplaceType::kReplaceConst: return ReplaceWithConstant(hlo); case ReplaceType::kReplaceParam: CHECK(hlo->parent() == root_instruction_->parent()) << "Replacing instructions at non-entry computation with " "parameters is not supported."; return ReplaceWithParameter(hlo); case ReplaceType::kReplaceZeroBroadcast: return ReplaceWithConstantBroadcast( hlo, ReplaceType::kReplaceZeroBroadcast); case ReplaceType::kReplaceRandomBroadcast: return ReplaceWithConstantBroadcast( hlo, ReplaceType::kReplaceRandomBroadcast); default: QCHECK(false) << "Unsupported replacement type"; } } return ReplaceWithParameter(hlo); } // Clone the visiting hlo and add it to computation builder. std::vector<HloInstruction*> new_operands; for (auto operand : hlo->operands()) { new_operands.push_back(clone_context_.GetInstruction(operand)); } auto instruction = hlo->CloneWithNewOperands(hlo->shape(), new_operands, &clone_context_); auto it = old_computations_to_builders_.find(hlo->parent()); CHECK(it != old_computations_to_builders_.end()); auto builder = it->second.get(); builder->AddInstruction(std::move(instruction)); // If the visiting `hlo` is the root instruction of a computation (except // for the root of the entry computation), we can build the new computation // now and put it in `clone_context_`. The entry computation would be built // in `FinishVisit()` when all the instructions are visited. if (hlo->IsRoot() && hlo != root_instruction_) { CHECK(clone_context_.FindComputation(hlo->parent()) == nullptr); auto new_computation = module_->AddEmbeddedComputation(builder->Build()); clone_context_.MapComputation(hlo->parent(), new_computation); } return absl::OkStatus(); } absl::Status FinishVisit(const HloInstruction* /*root*/) override { // Create the entry computation for the extracted module. auto new_entry_computation = module_->AddEntryComputation( old_computations_to_builders_.at(root_instruction_->parent())->Build()); clone_context_.MapComputation(root_instruction_->parent(), new_entry_computation); // Rename HLOs so that their name matches the original. By default, // HLOs get new unique names when adding a new entry computation to // a module. for (auto computation : old_module_->MakeComputationPostOrder()) { for (auto old_instruction : computation->MakeInstructionPostOrder()) { if (auto new_instruction = clone_context_.FindInstruction(old_instruction)) { new_instruction->SetAndSanitizeName(old_instruction->name()); } } } // For the extra created instructions (e.g., the ones created when replacing // with broadcasted zeros), we make sure they have unique names without // breaking the matches made at above code. for (HloInstruction* instruction : extra_created_instructions_) { module_->SetAndUniquifyInstrName(instruction, instruction->name()); } return absl::OkStatus(); } absl::Status ReplaceWithConstant(const HloInstruction* hlo) { absl::StatusOr<Literal> literal_status = MakeFakeLiteral(hlo->shape()); TF_CHECK_OK(literal_status.status()); auto new_const = HloInstruction::CreateConstant(std::move(literal_status.value())); clone_context_.MapInstruction(hlo, new_const.get()); auto it = old_computations_to_builders_.find(hlo->parent()); CHECK(it != old_computations_to_builders_.end()); auto builder = it->second.get(); builder->AddInstruction(std::move(new_const)); return absl::OkStatus(); } absl::Status ReplaceWithParameter(const HloInstruction* hlo) { CHECK(parameter_numbers_.contains(hlo->parent())); auto new_parameter = HloInstruction::CreateParameter( parameter_numbers_.at(hlo->parent())++, hlo->shape(), hlo->name()); clone_context_.MapInstruction(hlo, new_parameter.get()); CHECK(old_computations_to_builders_.contains(hlo->parent())); auto builder = old_computations_to_builders_[hlo->parent()].get(); builder->AddInstruction(std::move(new_parameter)); return absl::OkStatus(); } HloInstruction* ReplaceWithConstantBroadcastHelper( const Shape& shape, HloComputation::Builder* builder, ReplaceType replace_type) { if (shape.IsTuple()) { // If it is a tuple, recursively create a zero instruction. std::vector<HloInstruction*> tuple_operands; for (const auto& subshape : shape.tuple_shapes()) { tuple_operands.push_back(ReplaceWithConstantBroadcastHelper( subshape, builder, replace_type)); } auto zero_tuple = builder->AddInstruction(HloInstruction::CreateTuple(tuple_operands)); extra_created_instructions_.push_back(zero_tuple); return zero_tuple; } else { // If not a tuple, we need to create a zero constant of // `shape.element_type()`, and then broadcast it into the shape we want. // Create a constant of `shape.element_type()`. The constant could be // either a zero or a random number, depending on `replace_type`. Shape constant_shape = ShapeUtil::MakeShape(shape.element_type(), {}); HloInstruction* constant_instruction; CHECK(replace_type == ReplaceType::kReplaceZeroBroadcast || replace_type == ReplaceType::kReplaceRandomBroadcast); if (replace_type == ReplaceType::kReplaceZeroBroadcast) { constant_instruction = builder->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(constant_shape.element_type()))); } else { absl::StatusOr<Literal> literal_status = MakeFakeLiteral(constant_shape); TF_CHECK_OK(literal_status.status()); constant_instruction = builder->AddInstruction( HloInstruction::CreateConstant(std::move(literal_status.value()))); } extra_created_instructions_.push_back(constant_instruction); // Broadcast `constant_instruction` to create an hlo of the desired // shape. auto broadcast_constant_instruction = builder->AddInstruction( HloInstruction::CreateBroadcast(shape, constant_instruction, {})); extra_created_instructions_.push_back(broadcast_constant_instruction); return broadcast_constant_instruction; } } absl::Status ReplaceWithConstantBroadcast(const HloInstruction* hlo, ReplaceType replace_type) { CHECK(replace_type == ReplaceType::kReplaceZeroBroadcast || replace_type == ReplaceType::kReplaceRandomBroadcast); CHECK(old_computations_to_builders_.contains(hlo->parent())); auto builder = old_computations_to_builders_[hlo->parent()].get(); HloInstruction* zero_broadcast = ReplaceWithConstantBroadcastHelper(hlo->shape(), builder, replace_type); clone_context_.MapInstruction(hlo, zero_broadcast); return absl::OkStatus(); } void ComputeBoundary(const HloInstruction* root, int64_t limit, absl::flat_hash_set<const HloInstruction*>* boundary) { std::deque<const HloInstruction*> worklist; absl::flat_hash_map<const HloInstruction*, int64_t> visited; worklist.push_back(root); visited.emplace(root, 0); while (!worklist.empty()) { auto hlo = worklist.front(); worklist.pop_front(); int64_t hops = visited[hlo]; if (hops > limit) { boundary->insert(hlo); continue; } for (const HloInstruction* operand : hlo->operands()) { if (visited.count(operand)) { continue; } worklist.push_back(operand); visited.emplace(operand, hops + 1); } } } std::unique_ptr<HloModule> ExtractModule( const HloInstruction* instruction, int64_t height, ExtractSelector extract_selector, ReplaceTypeSelector replace_type_selector, bool cross_computation) { QCHECK(height == -1 || !cross_computation) << "Boundary cannnot be calculated across the computations."; absl::flat_hash_set<const HloInstruction*> boundary; if (height != -1) { ComputeBoundary(instruction, height, &boundary); } ExtractionVisitor visitor(instruction, &boundary, extract_selector, replace_type_selector); TF_CHECK_OK(instruction->Accept(&visitor, /*call_finish_visit=*/true, /*ignore_control_predecessors=*/false, /*cross_computation=*/cross_computation)); // The first pass may leave unused parameter instructions in the entry // computation. Do another extraction pass to remove unused parameters in the // entry computation. This is done because HloComputation does not allow // removing parameters after the computation has been built. ExtractionVisitor cleanup_visitor( visitor.module()->entry_computation()->root_instruction(), /*boundary=*/nullptr, /*extract_selector=*/nullptr, /*replace_type_selector=*/nullptr); TF_CHECK_OK(visitor.module()->entry_computation()->root_instruction()->Accept( &cleanup_visitor, /*call_finish_visit=*/true, /*ignore_control_predecessors=*/false, /*cross_computation=*/false)); HloVerifier verifier(/*layout_sensitive=*/false, /*allow_mixed_precision=*/true); TF_CHECK_OK(verifier.Run(cleanup_visitor.module()).status()); return cleanup_visitor.ConsumeModule(); }
#include "xla/tools/hlo_extractor.h" #include <memory> #include <string> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/tests/hlo_test_base.h" #include "tsl/platform/statusor.h" TEST_F(HloExtractorTest, ExtractWithConstant) { const std::string& hlo_string = R"( HloModule test ENTRY %entry { p = f32[4]{0} parameter(0) tanh = f32[4]{0} tanh(p) c = f32[4]{0} constant({1, 2, 3, 4}) ROOT add = f32[4]{0} add(tanh, c) } )"; TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> hlo_module, ParseAndReturnVerifiedModule(hlo_string)); { auto extracted_module = ExtractModule(FindInstruction(hlo_module.get(), "add"), /*height=*/0); EXPECT_THAT(extracted_module->entry_computation()->root_instruction(), op::Add(op::Parameter(0), op::Parameter(1))); } { auto extracted_module = ExtractModule(FindInstruction(hlo_module.get(), "add"), /*height=*/1); EXPECT_THAT(extracted_module->entry_computation()->root_instruction(), op::Add(op::Tanh(op::Parameter(0)), op::Constant())); } }
HloExtractorTest_HloSelector
xla/tools/hlo_extractor_test.cc
explicit ExtractionVisitor( const HloInstruction* root_instruction, absl::flat_hash_set<const HloInstruction*>* boundary, ExtractSelector extract_selector, ReplaceTypeSelector replace_type_selector) : root_instruction_(root_instruction), old_module_(root_instruction->GetModule()), module_(std::make_unique<HloModule>( "extracted", config_, std::make_unique<CompilationEnvironments>( old_module_->comp_envs()))), clone_context_(module_.get()), boundary_(boundary), extract_selector_(extract_selector), replace_type_selector_(replace_type_selector) { // Initialize the computation builder for every computations. for (auto computation : old_module_->computations()) { old_computations_to_builders_.insert( {computation, std::make_unique<HloComputation::Builder>(computation->name())}); } // Initialize the parameter counter for every computations. for (auto computation : old_module_->computations()) { parameter_numbers_[computation] = 0; } } absl::Status HandleParameter(const HloInstruction* parameter) override { // Entry parameters need renumbering. return ReplaceWithParameter(parameter); } absl::Status DefaultAction(const HloInstruction* hlo) override { // Replace the following two types of instructions with parameters/constants // (1) the instructions at the boundary with (2) the instructions that are // not selected by the hlo_selector. if ((boundary_ != nullptr && boundary_->contains(hlo) > 0) || (extract_selector_ != nullptr && !extract_selector_(hlo))) { if (replace_type_selector_ != nullptr) { switch (replace_type_selector_(hlo)) { case ReplaceType::kReplaceConst: return ReplaceWithConstant(hlo); case ReplaceType::kReplaceParam: CHECK(hlo->parent() == root_instruction_->parent()) << "Replacing instructions at non-entry computation with " "parameters is not supported."; return ReplaceWithParameter(hlo); case ReplaceType::kReplaceZeroBroadcast: return ReplaceWithConstantBroadcast( hlo, ReplaceType::kReplaceZeroBroadcast); case ReplaceType::kReplaceRandomBroadcast: return ReplaceWithConstantBroadcast( hlo, ReplaceType::kReplaceRandomBroadcast); default: QCHECK(false) << "Unsupported replacement type"; } } return ReplaceWithParameter(hlo); } // Clone the visiting hlo and add it to computation builder. std::vector<HloInstruction*> new_operands; for (auto operand : hlo->operands()) { new_operands.push_back(clone_context_.GetInstruction(operand)); } auto instruction = hlo->CloneWithNewOperands(hlo->shape(), new_operands, &clone_context_); auto it = old_computations_to_builders_.find(hlo->parent()); CHECK(it != old_computations_to_builders_.end()); auto builder = it->second.get(); builder->AddInstruction(std::move(instruction)); // If the visiting `hlo` is the root instruction of a computation (except // for the root of the entry computation), we can build the new computation // now and put it in `clone_context_`. The entry computation would be built // in `FinishVisit()` when all the instructions are visited. if (hlo->IsRoot() && hlo != root_instruction_) { CHECK(clone_context_.FindComputation(hlo->parent()) == nullptr); auto new_computation = module_->AddEmbeddedComputation(builder->Build()); clone_context_.MapComputation(hlo->parent(), new_computation); } return absl::OkStatus(); } absl::Status FinishVisit(const HloInstruction* /*root*/) override { // Create the entry computation for the extracted module. auto new_entry_computation = module_->AddEntryComputation( old_computations_to_builders_.at(root_instruction_->parent())->Build()); clone_context_.MapComputation(root_instruction_->parent(), new_entry_computation); // Rename HLOs so that their name matches the original. By default, // HLOs get new unique names when adding a new entry computation to // a module. for (auto computation : old_module_->MakeComputationPostOrder()) { for (auto old_instruction : computation->MakeInstructionPostOrder()) { if (auto new_instruction = clone_context_.FindInstruction(old_instruction)) { new_instruction->SetAndSanitizeName(old_instruction->name()); } } } // For the extra created instructions (e.g., the ones created when replacing // with broadcasted zeros), we make sure they have unique names without // breaking the matches made at above code. for (HloInstruction* instruction : extra_created_instructions_) { module_->SetAndUniquifyInstrName(instruction, instruction->name()); } return absl::OkStatus(); } absl::Status ReplaceWithConstant(const HloInstruction* hlo) { absl::StatusOr<Literal> literal_status = MakeFakeLiteral(hlo->shape()); TF_CHECK_OK(literal_status.status()); auto new_const = HloInstruction::CreateConstant(std::move(literal_status.value())); clone_context_.MapInstruction(hlo, new_const.get()); auto it = old_computations_to_builders_.find(hlo->parent()); CHECK(it != old_computations_to_builders_.end()); auto builder = it->second.get(); builder->AddInstruction(std::move(new_const)); return absl::OkStatus(); } absl::Status ReplaceWithParameter(const HloInstruction* hlo) { CHECK(parameter_numbers_.contains(hlo->parent())); auto new_parameter = HloInstruction::CreateParameter( parameter_numbers_.at(hlo->parent())++, hlo->shape(), hlo->name()); clone_context_.MapInstruction(hlo, new_parameter.get()); CHECK(old_computations_to_builders_.contains(hlo->parent())); auto builder = old_computations_to_builders_[hlo->parent()].get(); builder->AddInstruction(std::move(new_parameter)); return absl::OkStatus(); } HloInstruction* ReplaceWithConstantBroadcastHelper( const Shape& shape, HloComputation::Builder* builder, ReplaceType replace_type) { if (shape.IsTuple()) { // If it is a tuple, recursively create a zero instruction. std::vector<HloInstruction*> tuple_operands; for (const auto& subshape : shape.tuple_shapes()) { tuple_operands.push_back(ReplaceWithConstantBroadcastHelper( subshape, builder, replace_type)); } auto zero_tuple = builder->AddInstruction(HloInstruction::CreateTuple(tuple_operands)); extra_created_instructions_.push_back(zero_tuple); return zero_tuple; } else { // If not a tuple, we need to create a zero constant of // `shape.element_type()`, and then broadcast it into the shape we want. // Create a constant of `shape.element_type()`. The constant could be // either a zero or a random number, depending on `replace_type`. Shape constant_shape = ShapeUtil::MakeShape(shape.element_type(), {}); HloInstruction* constant_instruction; CHECK(replace_type == ReplaceType::kReplaceZeroBroadcast || replace_type == ReplaceType::kReplaceRandomBroadcast); if (replace_type == ReplaceType::kReplaceZeroBroadcast) { constant_instruction = builder->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(constant_shape.element_type()))); } else { absl::StatusOr<Literal> literal_status = MakeFakeLiteral(constant_shape); TF_CHECK_OK(literal_status.status()); constant_instruction = builder->AddInstruction( HloInstruction::CreateConstant(std::move(literal_status.value()))); } extra_created_instructions_.push_back(constant_instruction); // Broadcast `constant_instruction` to create an hlo of the desired // shape. auto broadcast_constant_instruction = builder->AddInstruction( HloInstruction::CreateBroadcast(shape, constant_instruction, {})); extra_created_instructions_.push_back(broadcast_constant_instruction); return broadcast_constant_instruction; } } absl::Status ReplaceWithConstantBroadcast(const HloInstruction* hlo, ReplaceType replace_type) { CHECK(replace_type == ReplaceType::kReplaceZeroBroadcast || replace_type == ReplaceType::kReplaceRandomBroadcast); CHECK(old_computations_to_builders_.contains(hlo->parent())); auto builder = old_computations_to_builders_[hlo->parent()].get(); HloInstruction* zero_broadcast = ReplaceWithConstantBroadcastHelper(hlo->shape(), builder, replace_type); clone_context_.MapInstruction(hlo, zero_broadcast); return absl::OkStatus(); } void ComputeBoundary(const HloInstruction* root, int64_t limit, absl::flat_hash_set<const HloInstruction*>* boundary) { std::deque<const HloInstruction*> worklist; absl::flat_hash_map<const HloInstruction*, int64_t> visited; worklist.push_back(root); visited.emplace(root, 0); while (!worklist.empty()) { auto hlo = worklist.front(); worklist.pop_front(); int64_t hops = visited[hlo]; if (hops > limit) { boundary->insert(hlo); continue; } for (const HloInstruction* operand : hlo->operands()) { if (visited.count(operand)) { continue; } worklist.push_back(operand); visited.emplace(operand, hops + 1); } } } std::unique_ptr<HloModule> ExtractModule( const HloInstruction* instruction, int64_t height, ExtractSelector extract_selector, ReplaceTypeSelector replace_type_selector, bool cross_computation) { QCHECK(height == -1 || !cross_computation) << "Boundary cannnot be calculated across the computations."; absl::flat_hash_set<const HloInstruction*> boundary; if (height != -1) { ComputeBoundary(instruction, height, &boundary); } ExtractionVisitor visitor(instruction, &boundary, extract_selector, replace_type_selector); TF_CHECK_OK(instruction->Accept(&visitor, /*call_finish_visit=*/true, /*ignore_control_predecessors=*/false, /*cross_computation=*/cross_computation)); // The first pass may leave unused parameter instructions in the entry // computation. Do another extraction pass to remove unused parameters in the // entry computation. This is done because HloComputation does not allow // removing parameters after the computation has been built. ExtractionVisitor cleanup_visitor( visitor.module()->entry_computation()->root_instruction(), /*boundary=*/nullptr, /*extract_selector=*/nullptr, /*replace_type_selector=*/nullptr); TF_CHECK_OK(visitor.module()->entry_computation()->root_instruction()->Accept( &cleanup_visitor, /*call_finish_visit=*/true, /*ignore_control_predecessors=*/false, /*cross_computation=*/false)); HloVerifier verifier(/*layout_sensitive=*/false, /*allow_mixed_precision=*/true); TF_CHECK_OK(verifier.Run(cleanup_visitor.module()).status()); return cleanup_visitor.ConsumeModule(); }
#include "xla/tools/hlo_extractor.h" #include <memory> #include <string> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/tests/hlo_test_base.h" #include "tsl/platform/statusor.h"
HloExtractorTest_ReplaceTupleWithConstant
xla/tools/hlo_extractor_test.cc
explicit ExtractionVisitor( const HloInstruction* root_instruction, absl::flat_hash_set<const HloInstruction*>* boundary, ExtractSelector extract_selector, ReplaceTypeSelector replace_type_selector) : root_instruction_(root_instruction), old_module_(root_instruction->GetModule()), module_(std::make_unique<HloModule>( "extracted", config_, std::make_unique<CompilationEnvironments>( old_module_->comp_envs()))), clone_context_(module_.get()), boundary_(boundary), extract_selector_(extract_selector), replace_type_selector_(replace_type_selector) { // Initialize the computation builder for every computations. for (auto computation : old_module_->computations()) { old_computations_to_builders_.insert( {computation, std::make_unique<HloComputation::Builder>(computation->name())}); } // Initialize the parameter counter for every computations. for (auto computation : old_module_->computations()) { parameter_numbers_[computation] = 0; } } absl::Status HandleParameter(const HloInstruction* parameter) override { // Entry parameters need renumbering. return ReplaceWithParameter(parameter); } absl::Status DefaultAction(const HloInstruction* hlo) override { // Replace the following two types of instructions with parameters/constants // (1) the instructions at the boundary with (2) the instructions that are // not selected by the hlo_selector. if ((boundary_ != nullptr && boundary_->contains(hlo) > 0) || (extract_selector_ != nullptr && !extract_selector_(hlo))) { if (replace_type_selector_ != nullptr) { switch (replace_type_selector_(hlo)) { case ReplaceType::kReplaceConst: return ReplaceWithConstant(hlo); case ReplaceType::kReplaceParam: CHECK(hlo->parent() == root_instruction_->parent()) << "Replacing instructions at non-entry computation with " "parameters is not supported."; return ReplaceWithParameter(hlo); case ReplaceType::kReplaceZeroBroadcast: return ReplaceWithConstantBroadcast( hlo, ReplaceType::kReplaceZeroBroadcast); case ReplaceType::kReplaceRandomBroadcast: return ReplaceWithConstantBroadcast( hlo, ReplaceType::kReplaceRandomBroadcast); default: QCHECK(false) << "Unsupported replacement type"; } } return ReplaceWithParameter(hlo); } // Clone the visiting hlo and add it to computation builder. std::vector<HloInstruction*> new_operands; for (auto operand : hlo->operands()) { new_operands.push_back(clone_context_.GetInstruction(operand)); } auto instruction = hlo->CloneWithNewOperands(hlo->shape(), new_operands, &clone_context_); auto it = old_computations_to_builders_.find(hlo->parent()); CHECK(it != old_computations_to_builders_.end()); auto builder = it->second.get(); builder->AddInstruction(std::move(instruction)); // If the visiting `hlo` is the root instruction of a computation (except // for the root of the entry computation), we can build the new computation // now and put it in `clone_context_`. The entry computation would be built // in `FinishVisit()` when all the instructions are visited. if (hlo->IsRoot() && hlo != root_instruction_) { CHECK(clone_context_.FindComputation(hlo->parent()) == nullptr); auto new_computation = module_->AddEmbeddedComputation(builder->Build()); clone_context_.MapComputation(hlo->parent(), new_computation); } return absl::OkStatus(); } absl::Status FinishVisit(const HloInstruction* /*root*/) override { // Create the entry computation for the extracted module. auto new_entry_computation = module_->AddEntryComputation( old_computations_to_builders_.at(root_instruction_->parent())->Build()); clone_context_.MapComputation(root_instruction_->parent(), new_entry_computation); // Rename HLOs so that their name matches the original. By default, // HLOs get new unique names when adding a new entry computation to // a module. for (auto computation : old_module_->MakeComputationPostOrder()) { for (auto old_instruction : computation->MakeInstructionPostOrder()) { if (auto new_instruction = clone_context_.FindInstruction(old_instruction)) { new_instruction->SetAndSanitizeName(old_instruction->name()); } } } // For the extra created instructions (e.g., the ones created when replacing // with broadcasted zeros), we make sure they have unique names without // breaking the matches made at above code. for (HloInstruction* instruction : extra_created_instructions_) { module_->SetAndUniquifyInstrName(instruction, instruction->name()); } return absl::OkStatus(); } absl::Status ReplaceWithConstant(const HloInstruction* hlo) { absl::StatusOr<Literal> literal_status = MakeFakeLiteral(hlo->shape()); TF_CHECK_OK(literal_status.status()); auto new_const = HloInstruction::CreateConstant(std::move(literal_status.value())); clone_context_.MapInstruction(hlo, new_const.get()); auto it = old_computations_to_builders_.find(hlo->parent()); CHECK(it != old_computations_to_builders_.end()); auto builder = it->second.get(); builder->AddInstruction(std::move(new_const)); return absl::OkStatus(); } absl::Status ReplaceWithParameter(const HloInstruction* hlo) { CHECK(parameter_numbers_.contains(hlo->parent())); auto new_parameter = HloInstruction::CreateParameter( parameter_numbers_.at(hlo->parent())++, hlo->shape(), hlo->name()); clone_context_.MapInstruction(hlo, new_parameter.get()); CHECK(old_computations_to_builders_.contains(hlo->parent())); auto builder = old_computations_to_builders_[hlo->parent()].get(); builder->AddInstruction(std::move(new_parameter)); return absl::OkStatus(); } HloInstruction* ReplaceWithConstantBroadcastHelper( const Shape& shape, HloComputation::Builder* builder, ReplaceType replace_type) { if (shape.IsTuple()) { // If it is a tuple, recursively create a zero instruction. std::vector<HloInstruction*> tuple_operands; for (const auto& subshape : shape.tuple_shapes()) { tuple_operands.push_back(ReplaceWithConstantBroadcastHelper( subshape, builder, replace_type)); } auto zero_tuple = builder->AddInstruction(HloInstruction::CreateTuple(tuple_operands)); extra_created_instructions_.push_back(zero_tuple); return zero_tuple; } else { // If not a tuple, we need to create a zero constant of // `shape.element_type()`, and then broadcast it into the shape we want. // Create a constant of `shape.element_type()`. The constant could be // either a zero or a random number, depending on `replace_type`. Shape constant_shape = ShapeUtil::MakeShape(shape.element_type(), {}); HloInstruction* constant_instruction; CHECK(replace_type == ReplaceType::kReplaceZeroBroadcast || replace_type == ReplaceType::kReplaceRandomBroadcast); if (replace_type == ReplaceType::kReplaceZeroBroadcast) { constant_instruction = builder->AddInstruction(HloInstruction::CreateConstant( LiteralUtil::Zero(constant_shape.element_type()))); } else { absl::StatusOr<Literal> literal_status = MakeFakeLiteral(constant_shape); TF_CHECK_OK(literal_status.status()); constant_instruction = builder->AddInstruction( HloInstruction::CreateConstant(std::move(literal_status.value()))); } extra_created_instructions_.push_back(constant_instruction); // Broadcast `constant_instruction` to create an hlo of the desired // shape. auto broadcast_constant_instruction = builder->AddInstruction( HloInstruction::CreateBroadcast(shape, constant_instruction, {})); extra_created_instructions_.push_back(broadcast_constant_instruction); return broadcast_constant_instruction; } } absl::Status ReplaceWithConstantBroadcast(const HloInstruction* hlo, ReplaceType replace_type) { CHECK(replace_type == ReplaceType::kReplaceZeroBroadcast || replace_type == ReplaceType::kReplaceRandomBroadcast); CHECK(old_computations_to_builders_.contains(hlo->parent())); auto builder = old_computations_to_builders_[hlo->parent()].get(); HloInstruction* zero_broadcast = ReplaceWithConstantBroadcastHelper(hlo->shape(), builder, replace_type); clone_context_.MapInstruction(hlo, zero_broadcast); return absl::OkStatus(); } void ComputeBoundary(const HloInstruction* root, int64_t limit, absl::flat_hash_set<const HloInstruction*>* boundary) { std::deque<const HloInstruction*> worklist; absl::flat_hash_map<const HloInstruction*, int64_t> visited; worklist.push_back(root); visited.emplace(root, 0); while (!worklist.empty()) { auto hlo = worklist.front(); worklist.pop_front(); int64_t hops = visited[hlo]; if (hops > limit) { boundary->insert(hlo); continue; } for (const HloInstruction* operand : hlo->operands()) { if (visited.count(operand)) { continue; } worklist.push_back(operand); visited.emplace(operand, hops + 1); } } } std::unique_ptr<HloModule> ExtractModule( const HloInstruction* instruction, int64_t height, ExtractSelector extract_selector, ReplaceTypeSelector replace_type_selector, bool cross_computation) { QCHECK(height == -1 || !cross_computation) << "Boundary cannnot be calculated across the computations."; absl::flat_hash_set<const HloInstruction*> boundary; if (height != -1) { ComputeBoundary(instruction, height, &boundary); } ExtractionVisitor visitor(instruction, &boundary, extract_selector, replace_type_selector); TF_CHECK_OK(instruction->Accept(&visitor, /*call_finish_visit=*/true, /*ignore_control_predecessors=*/false, /*cross_computation=*/cross_computation)); // The first pass may leave unused parameter instructions in the entry // computation. Do another extraction pass to remove unused parameters in the // entry computation. This is done because HloComputation does not allow // removing parameters after the computation has been built. ExtractionVisitor cleanup_visitor( visitor.module()->entry_computation()->root_instruction(), /*boundary=*/nullptr, /*extract_selector=*/nullptr, /*replace_type_selector=*/nullptr); TF_CHECK_OK(visitor.module()->entry_computation()->root_instruction()->Accept( &cleanup_visitor, /*call_finish_visit=*/true, /*ignore_control_predecessors=*/false, /*cross_computation=*/false)); HloVerifier verifier(/*layout_sensitive=*/false, /*allow_mixed_precision=*/true); TF_CHECK_OK(verifier.Run(cleanup_visitor.module()).status()); return cleanup_visitor.ConsumeModule(); }
#include "xla/tools/hlo_extractor.h" #include <memory> #include <string> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/tests/hlo_test_base.h" #include "tsl/platform/statusor.h" TEST_F(HloExtractorTest, ReplaceTupleWithConstant) { const std::string& hlo_string = R"( HloModule test ENTRY %entry { param.0 = f32[4]{0} parameter(0) tuple.0 = (f32[4]{0}, f32[4]{0}) rng-bit-generator(f32[4]{0} param.0), algorithm=rng_default negate = f32[4]{0} negate(f32[4]{0} param.0) tuple.1 = ((f32[4]{0}, f32[4]{0}), f32[4]{0}) tuple(tuple.0, negate) element = f32[4]{0} get-tuple-element(((f32[4]{0}, f32[4]{0}), f32[4]{0}) tuple.1), index=1 ROOT add = f32[4]{0} add(element, param.0) } )"; TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> hlo_module, ParseAndReturnVerifiedModule(hlo_string)); // Testing kReplaceConst. { auto hlo_selector = [](const HloInstruction* hlo_inst) -> bool { return hlo_inst->opcode() != HloOpcode::kTuple; }; auto replace_type_selector = [](const HloInstruction* hlo_inst) -> ReplaceType { return ReplaceType::kReplaceConst; }; auto extracted_module = ExtractModule(FindInstruction(hlo_module.get(), "add"), /*height=*/-1, hlo_selector, replace_type_selector); EXPECT_THAT(extracted_module->entry_computation()->root_instruction(), op::Add(op::GetTupleElement(op::Constant()), op::Parameter())); } // Testing kReplaceZeroBroadcast -- replace a scalar (`element`) with // a broadcasted zero. { auto hlo_selector = [](const HloInstruction* hlo_inst) -> bool { return hlo_inst->opcode() != HloOpcode::kGetTupleElement; }; auto replace_type_selector = [](const HloInstruction* hlo_inst) -> ReplaceType { return ReplaceType::kReplaceZeroBroadcast; }; auto extracted_module = ExtractModule(FindInstruction(hlo_module.get(), "add"), /*height=*/-1, hlo_selector, replace_type_selector); EXPECT_THAT(extracted_module->entry_computation()->root_instruction(), op::Add(op::Broadcast(), op::Parameter())); } // Testing kReplaceRandomBroadcast -- replace a scalar (`element`) with a // broadcasted random constant. { auto hlo_selector = [](const HloInstruction* hlo_inst) -> bool { return hlo_inst->opcode() != HloOpcode::kGetTupleElement; }; auto replace_type_selector = [](const HloInstruction* hlo_inst) -> ReplaceType { return ReplaceType::kReplaceRandomBroadcast; }; auto extracted_module = ExtractModule(FindInstruction(hlo_module.get(), "add"), /*height=*/-1, hlo_selector, replace_type_selector); EXPECT_THAT(extracted_module->entry_computation()->root_instruction(), op::Add(op::Broadcast(), op::Parameter())); } // Testing kReplaceZeroBroadcast -- replace a tuple op (`tuple.1`) with zeros. { auto hlo_selector = [](const HloInstruction* hlo_inst) -> bool { return hlo_inst->opcode() != HloOpcode::kTuple; }; auto replace_type_selector = [](const HloInstruction* hlo_inst) -> ReplaceType { return ReplaceType::kReplaceZeroBroadcast; }; auto extracted_module = ExtractModule(FindInstruction(hlo_module.get(), "add"), /*height=*/-1, hlo_selector, replace_type_selector); EXPECT_THAT( extracted_module->entry_computation()->root_instruction(), op::Add(op::GetTupleElement(op::Tuple(op::Tuple(), op::Broadcast())), op::Parameter())); } // Testing kReplaceRandomBroadcast -- replace a tuple op (`tuple.1`) with a // broadcasted random constant. { auto hlo_selector = [](const HloInstruction* hlo_inst) -> bool { return hlo_inst->opcode() != HloOpcode::kTuple; }; auto replace_type_selector = [](const HloInstruction* hlo_inst) -> ReplaceType { return ReplaceType::kReplaceRandomBroadcast; }; auto extracted_module = ExtractModule(FindInstruction(hlo_module.get(), "add"), /*height=*/-1, hlo_selector, replace_type_selector); EXPECT_THAT( extracted_module->entry_computation()->root_instruction(), op::Add(op::GetTupleElement(op::Tuple(op::Tuple(), op::Broadcast())), op::Parameter())); } }
HloModuleLoaderTest_StripsLogHeaders
xla/tools/hlo_module_loader_test.cc
std::string StripLogHeaders(std::string_view hlo_string) { // I0521 12:04:45.883483 1509 service.cc:186] ... static RE2* matcher = new RE2( "[IWEF]\\d{4} " "\\d{2}:\\d{2}:\\d{2}\\.\\d+\\s+\\d+\\s+[^:]+:\\d+\\]\\s?(.*)"); std::string_view matches[4]; std::vector<std::string> lines = absl::StrSplit(hlo_string, '\n'); for (auto& line : lines) { if (matcher->Match(line, 0, line.size(), RE2::ANCHOR_START, matches, 4)) { line = std::string(matches[1]); } } return absl::StrJoin(lines, "\n", [](std::string* out, const std::string& line) { absl::StrAppend(out, line); }); } absl::StatusOr<std::unique_ptr<HloModule>> LoadModuleFromData( const std::string& data, std::string_view format, const hlo_module_loader_details::Config& ovr_config, const std::function<void(HloModuleConfig*)>& config_modifier_hook, BufferAssignmentProto* buffer_assignment_proto) { DebugOptions debug_options = GetDebugOptionsFromFlags(); std::unique_ptr<HloModule> module; if (format == "hlo" || format == "txt") { std::string hlo_string = StripLogHeaders(data); HloModuleConfig config; config.set_debug_options(debug_options); TF_RETURN_IF_ERROR(OverrideConfig(ovr_config, &config)); if (config_modifier_hook) { config_modifier_hook(&config); } TF_ASSIGN_OR_RETURN(module, ParseAndReturnUnverifiedModule(hlo_string, config)); } else { HloSnapshot proto; if (format == "pb") { if (!proto.ParseFromString(data) && !proto.mutable_hlo()->ParseFromString(data) && !proto.mutable_hlo()->mutable_hlo_module()->ParseFromString(data)) { return InvalidArgument("Failed to parse input as HLO protobuf binary"); } if (buffer_assignment_proto != nullptr) { if (proto.hlo().has_buffer_assignment()) { *buffer_assignment_proto = proto.hlo().buffer_assignment(); } else { return InvalidArgument( "Expected buffer assignment in HLO protobuf binary."); } } } else if (format == "pbtxt") { if (!tsl::protobuf::TextFormat::ParseFromString(data, &proto) && !tsl::protobuf::TextFormat::ParseFromString(data, proto.mutable_hlo()) && !tsl::protobuf::TextFormat::ParseFromString( data, proto.mutable_hlo()->mutable_hlo_module())) { return InvalidArgument("Failed to parse input as HLO protobuf text"); } } else { return InvalidArgument( "Invalid format from file extension: '%s'. Expected: hlo, txt, pb, " "or pbtxt", format); } TF_ASSIGN_OR_RETURN(HloModuleConfig config, HloModule::CreateModuleConfigFromProto( proto.hlo().hlo_module(), debug_options)); TF_RETURN_IF_ERROR(OverrideConfig(ovr_config, &config)); if (config_modifier_hook) { config_modifier_hook(&config); } TF_ASSIGN_OR_RETURN( module, HloModule::CreateFromProto(proto.hlo().hlo_module(), config)); } return std::move(module); } absl::StatusOr<std::unique_ptr<HloModule>> LoadModuleFromFile( const std::string& path, std::string format, const hlo_module_loader_details::Config& ovr_config, const std::function<void(HloModuleConfig*)>& config_modifier_hook, BufferAssignmentProto* buffer_assignment_proto) { std::string data; if (format.empty()) { format = std::string(tsl::io::Extension(path)); } TF_RETURN_IF_ERROR(tsl::ReadFileToString(tsl::Env::Default(), path, &data)); return LoadModuleFromData(data, format, ovr_config, config_modifier_hook, buffer_assignment_proto); } LoadInputFromData(const std::string& data, std::string_view format) { HloSnapshot proto; if (format == "pb") { if (!proto.ParseFromString(data) && !proto.mutable_hlo()->ParseFromString(data) && !proto.mutable_hlo()->mutable_hlo_module()->ParseFromString(data)) { return InvalidArgument("Failed to parse input as HLO protobuf binary"); } } else if (format == "pbtxt") { if (!tsl::protobuf::TextFormat::ParseFromString(data, &proto) && !tsl::protobuf::TextFormat::ParseFromString(data, proto.mutable_hlo()) && !tsl::protobuf::TextFormat::ParseFromString( data, proto.mutable_hlo()->mutable_hlo_module())) { return InvalidArgument("Failed to parse input as HLO protobuf text"); } } else { return InvalidArgument( "Invalid format from file extension: '%s'. Expected: pb, " "or pbtxt", format); } auto iteration_literals_proto = std::make_unique<RunHloModuleIterationLiterals>(); for (const auto& i : proto.arguments()) { *iteration_literals_proto->add_arguments() = i; } return std::move(iteration_literals_proto); } LoadInputFromFile(const std::string& path, std::string format) { std::string data; if (format.empty()) { format = std::string(tsl::io::Extension(path)); } TF_RETURN_IF_ERROR(tsl::ReadFileToString(tsl::Env::Default(), path, &data)); return LoadInputFromData(data, format); }
#include "xla/tools/hlo_module_loader.h" #include <string> #include "xla/tests/hlo_test_base.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/test.h" class HloModuleLoaderTest : public HloTestBase {}; TEST_F(HloModuleLoaderTest, StripsLogHeaders) { const std::string& hlo_string = R"( I0521 12:04:45.883483 1509 service.cc:186] HloModule test_log_stripping I0521 12:04:45.883483 1509 service.cc:186] I0521 12:04:45.883483 1509 service.cc:186] ENTRY entry { I0521 12:04:45.883483 1509 service.cc:186] p0 = f32[4]{0} parameter(0) I0521 12:04:45.883483 1509 service.cc:186] p1 = f32[4]{0} parameter(1) I0521 12:04:45.883483 1509 service.cc:186] add = f32[4]{0} add(p0, p1) I0521 12:04:45.883483 1509 service.cc:186] ROOT rooty = (f32[4]{0}, f32[4]{0}) tuple(p1, add) I0521 12:04:45.883483 1509 service.cc:186] } )"; TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> hlo_module, LoadModuleFromData(hlo_string, "txt")); EXPECT_NE(FindInstruction(hlo_module.get(), "p0"), nullptr); EXPECT_NE(FindInstruction(hlo_module.get(), "p1"), nullptr); EXPECT_NE(FindInstruction(hlo_module.get(), "add"), nullptr); EXPECT_NE(FindInstruction(hlo_module.get(), "rooty"), nullptr); }
HloSlicerTest_ForwardSlicingNearestCommonAncestor
xla/tools/hlo_slicer_test.cc
void ReduceTupleParameterHelper(HloModule* hlo_module, HloInstruction* tuple_parameter) { // Only handle the case where all the uses are GetTupleElement. for (HloInstruction* user_inst : tuple_parameter->users()) { if (user_inst->opcode() != HloOpcode::kGetTupleElement) { return; } } VLOG(1) << "Parameter instruction to be reduced: " << tuple_parameter->ToString() << " shape size: " << tuple_parameter->shape().tuple_shapes_size() << " users size: " << tuple_parameter->users().size(); // Collect the shapes of the elements that have users. std::vector<Shape> used_shapes; for (HloInstruction* user_inst : tuple_parameter->users()) { used_shapes.push_back(user_inst->shape()); } // Change the shape of `tuple_parameter` to only include the shape of elements // that have users. Shape new_tuple_shape = ShapeUtil::MakeTupleShape(absl::MakeSpan(used_shapes)); tuple_parameter->mutable_shape()->mutable_tuple_shapes()->clear(); for (const auto& shape : used_shapes) { tuple_parameter->mutable_shape()->mutable_tuple_shapes()->push_back(shape); } // Update the tuple index of all of the users of `tuple_parameter`, so that // they index into the right shape. for (int i = 0; i < tuple_parameter->users().size(); ++i) { tuple_parameter->users()[i]->set_tuple_index(i); } // Update HloModule shape. hlo_module->mutable_config().SetComputationLayoutIfExists( hlo_module->entry_computation()->ComputeProgramShape()); } VLOG(1) << "Parameter instruction to be reduced: " void ReduceTupleParameter(HloModule* hlo_module) { // Collect all the parameters instructions of tuple type. std::vector<HloInstruction*> tuple_parameters; for (HloInstruction* parameter : hlo_module->entry_computation()->parameter_instructions()) { if (parameter->shape().IsTuple()) { tuple_parameters.push_back(parameter); } } // For each parameter, invokes `ReduceTupleParameterHelper` to reduce its size // of dimensions. No instruction is added or removed from `hlo_module` during // this process, only shapes of parameter instructions and tuple indices of // their uses are updated. for (HloInstruction* tuple_parameter : tuple_parameters) { ReduceTupleParameterHelper(hlo_module, tuple_parameter); } } HloInstruction* FindShardingInstruction(HloModule* hlo_module) { for (HloComputation* computation : hlo_module->computations()) { for (HloInstruction* instruction : computation->instructions()) { if (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == "Sharding") { CHECK_EQ(instruction->operand_count(), 1); return instruction; } } } return nullptr; } void RemoveSharding(HloModule* hlo_module) { while (HloInstruction* custom_call_instruction = FindShardingInstruction(hlo_module)) { // Replace its uses with its operand. for (HloInstruction* user_instruction : custom_call_instruction->users()) { CHECK_OK(custom_call_instruction->ReplaceUseWith( user_instruction, custom_call_instruction->mutable_operand(0))); } // Detach the custom-call from computation. custom_call_instruction->DetachFromOperandsAndUsers(); CHECK_OK(custom_call_instruction->parent()->RemoveInstruction( custom_call_instruction)); VLOG(1) << "Removed sharding custom-call: " << custom_call_instruction->ToString(); // Verify if the module is still valid. HloVerifier verifier(/*layout_sensitive=*/false, /*allow_mixed_precision=*/true); TF_CHECK_OK(verifier.Run(hlo_module).status()); } } VLOG(1) << "Removed sharding custom-call: " void IntraComputationSlicing( const HloComputation* computation, absl::flat_hash_set<const HloInstruction*>& sliced_instructions, absl::flat_hash_set<const HloInstruction*>& frontier_instructions, bool forward_slice, FrontierSelector frontier_selector, bool ignore_control_dependency) { std::deque<const HloInstruction*> worklist(sliced_instructions.begin(), sliced_instructions.end()); while (!worklist.empty()) { const HloInstruction* inst = worklist.back(); worklist.pop_back(); // If `inst` is at the frontier, bookkeep it, and continue. if (frontier_selector && !frontier_selector(inst)) { frontier_instructions.insert(inst); continue; } // Initialize data-dependent instructions std::vector<HloInstruction*> instructions_to_propagate = forward_slice ? std::vector<HloInstruction*>(inst->users().begin(), inst->users().end()) : std::vector<HloInstruction*>(inst->operands().begin(), inst->operands().end()); // Append control-dependent instructions if necessary if (!ignore_control_dependency) { if (forward_slice) { instructions_to_propagate.insert(instructions_to_propagate.end(), inst->control_successors().begin(), inst->control_successors().end()); } else { instructions_to_propagate.insert(instructions_to_propagate.end(), inst->control_predecessors().begin(), inst->control_predecessors().end()); } } for (auto next_inst : instructions_to_propagate) { if (!sliced_instructions.contains(next_inst)) { worklist.push_front(next_inst); sliced_instructions.insert(next_inst); } } } } SliceOutput SliceModuleHelper( const HloModule* hlo_module, absl::Span<const HloInstruction*> slice_starting_instructions, FrontierSelector frontier_selector, bool ignore_control_dependency, bool forward_slice, bool nearest_common_ancestor_as_root) { // Initialize `sliced_computation_instructions_map`, which keeps track of all // the sliced instructions. absl::flat_hash_map<const HloComputation*, absl::flat_hash_set<const HloInstruction*>> sliced_computation_instructions_map; for (auto inst : slice_starting_instructions) { sliced_computation_instructions_map[inst->parent()].insert(inst); } // Initialize `frontier_computation_instructions_map`. absl::flat_hash_map<const HloComputation*, absl::flat_hash_set<const HloInstruction*>> frontier_computation_instructions_map; // Build call graph. std::unique_ptr<CallGraph> call_graph = CallGraph::Build(hlo_module); // Traverse computations in the post-order(forward slicing) or // reverse post-order(backward slicing) manner, and conduct intra-computation // slicing in that order. // // Post-order guarantees that when computation `a` is visited, all of its // callee computations have been visited, thus all the necessary propagation // to `a` has been conducted (i.e., the sliced caller instruction in `a` has // been marked, which serve as the starting point in // `IntraComputationSlicing`). // // Similarly, reverse post-order guarantees that when computation `a` is // visited, all of its caller computations have been visited, thus its root // instruction has been marked, which serve as the starting point in // `IntraComputationSlicing`. std::vector<HloComputation*> post_order_computations = hlo_module->MakeComputationPostOrder(); std::vector<HloComputation*> computations_to_traverse = forward_slice ? post_order_computations : std::vector<HloComputation*>(post_order_computations.rbegin(), post_order_computations.rend()); // If `nearest_common_ancestor_as_root` is enabled, we compute the // HloComputations that hold the `nearest_common_ancestor` instruction, which // are the stopping points when iterating through `computations_to_traverse`. absl::flat_hash_set<const HloComputation*> nearest_common_ancestor_computations; if (nearest_common_ancestor_as_root) { std::vector<const HloComputation*> starting_computations; for (const auto& [computation, instructions] : sliced_computation_instructions_map) { starting_computations.push_back(computation); } nearest_common_ancestor_computations = call_graph->NearestCommonAncestorComputations(starting_computations); CHECK(!nearest_common_ancestor_computations.empty()); } for (auto computation : computations_to_traverse) { if (sliced_computation_instructions_map.contains(computation)) { auto slicing_starting_instructions = std::vector<const HloInstruction*>( sliced_computation_instructions_map[computation].begin(), sliced_computation_instructions_map[computation].end()); // Do intra-computation slicing, starting from the instructions that has // been inserted in `sliced_computation_instructions_map[computation]`. IntraComputationSlicing( computation, sliced_computation_instructions_map[computation], frontier_computation_instructions_map[computation], forward_slice, frontier_selector, ignore_control_dependency); // The block below propagate the slicing results from the current visiting // computation to the next ones. if (forward_slice) { // Check if the current computation is one of the // `nearest_common_ancestor_computations`. If yes, we find the // `nearest_common_ancestor` as an instruction, and stop here. if (nearest_common_ancestor_as_root && nearest_common_ancestor_computations.contains(computation)) { // We use one of the nearest common ancestor instructions. const HloInstruction* nearest_common_ancestor_instruction = *(call_graph->NearestCommonAncestorInstructions( slicing_starting_instructions)) .begin(); CHECK_NE(nearest_common_ancestor_instruction, nullptr); return SliceOutput{sliced_computation_instructions_map, frontier_computation_instructions_map, nearest_common_ancestor_instruction}; } // Skip propagating if the ROOT instruction of the current computation // is NOT sliced. It is either because (1) the sliced instructions are // actually dead code or (2) `frontier_selector` finds frontier and stop // propagation. The found frontier could be at the root instruction, and // in this case, we stop propagation. if (!sliced_computation_instructions_map[computation].contains( computation->root_instruction()) || frontier_computation_instructions_map[computation].contains( computation->root_instruction())) { continue; } // Continue propagating to successors of the current computation, by // inserting its caller computation into // `sliced_computation_instructions_map`, and inserting the caller // instructions as the starting points for intra-computation slicing. for (auto caller_inst : call_graph->GetComputationCallers(computation)) { sliced_computation_instructions_map[caller_inst->parent()].insert( caller_inst); } } if (!forward_slice) { // Propagate to the callee computation of the current computation // that the sliced instructions invoke, by inserting its callee // computation into `sliced_computation_instructions_map`, and inserting // the root instruction of the callee computation as the starting points // for later intra-computation slicing. for (const auto& callsite : call_graph->GetNode(computation).callsites()) { if (sliced_computation_instructions_map[computation].contains( callsite.instruction())) { for (auto callee : callsite.called_computations()) { sliced_computation_instructions_map[callee].insert( callee->root_instruction()); } } } } } } return SliceOutput{sliced_computation_instructions_map, frontier_computation_instructions_map}; } SliceOutput SliceModule( const HloModule* hlo_module, absl::Span<const HloInstruction*> slice_starting_instructions, FrontierSelector frontier_selector, bool ignore_control_dependency, bool forward_slice, bool nearest_common_ancestor_as_root) { if (forward_slice) { if (!nearest_common_ancestor_as_root) { // Forward slicing with the original root as the root. return SliceModuleHelper(hlo_module, slice_starting_instructions, frontier_selector, ignore_control_dependency, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/false); } else { // Forward slicing with the nearest common ancestor (NCA) as the root. // // Internally, this feature is implemented by the following two steps: // 1. Conducting a pass of forward slicing and looking for the NCA // instruction. We first compute the "NCA computation", which is the // NCA, of the computations that hold the // `slice_starting_instructions`. This computation is achieved by // invoking "NearestCommonAncestorComputations" in the call graph. // Then, when we reach the "NCA computation", we compute the NCA of // the instructions that calls the computations which are on the path // from the `slice_starting_instructions` to this NCA computation. // 2. The slice from step 1 contains some redundant instructions, // because, when we do forward slicing, we do not know the exact path // to the NCA, and there could some nodes that cannot be reached from // the NCA. Therefore, in this step, we conduct a pass of backward // slicing from the NCA and filter out the redundant instructions, by // taking the intersection between the backward slicing results and // the forward slicing results from step 1. // Sanity check. CHECK(forward_slice) << "Option `nearest_common_ancestor_as_root` can " "only be enabled when " "forward slicing"; CHECK((frontier_selector == nullptr)) << "Option `nearest_common_ancestor_as_root` can not be specified " "with `frontier_selector`"; // Forward slicing to identify nearest common ancestor SliceOutput forward_slice_output = SliceModuleHelper(hlo_module, slice_starting_instructions, /*frontier_selector=*/nullptr, ignore_control_dependency, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/true); std::vector<const HloInstruction*> nearest_common_ancestor( {forward_slice_output.nearest_common_ancestor_root()}); CHECK_EQ(nearest_common_ancestor.size(), 1); // Backward slicing from the nearest common ancestor to filter out // the redundant computations/instructions in the sliced result in step 1. SliceOutput backward_slice_output = SliceModuleHelper(hlo_module, /*slice_starting_instructions=*/ absl::MakeSpan(nearest_common_ancestor), /*frontier_selector=*/nullptr, ignore_control_dependency, /*forward_slice=*/false, /*nearest_common_ancestor_as_root=*/false); // Intersect the sliced instructions between forward slicing pass and // backward slicing pass as the new sliced instructions, and return the // new SliceOutput. return SliceOutput{SliceOutput::IntersectSlicedInstructions( forward_slice_output, backward_slice_output), backward_slice_output.frontier_instructions(), forward_slice_output.nearest_common_ancestor_root()}; } } else { // Backward slicing. return SliceModuleHelper(hlo_module, slice_starting_instructions, frontier_selector, ignore_control_dependency, /*forward_slice=*/false, /*nearest_common_ancestor_as_root=*/false); } } std::vector<std::unique_ptr<HloModule>> SliceModuleAndExtract( const HloModule* hlo_module, absl::Span<const HloInstruction*> slice_starting_instructions, const SlicingConfiguration& slicing_configuration) { std::vector<std::unique_ptr<HloModule>> sliced_modules; // Group `slice_starting_instructions` based on `slicing_group` configuration. int slicing_group = slicing_configuration.slicing_group; CHECK(slicing_group >= 1 || slicing_group == -1); std::vector<absl::Span<const HloInstruction*>> grouped_instructions; if (slicing_group == -1) { grouped_instructions = {slice_starting_instructions}; } else { for (int i = 0; i < slice_starting_instructions.size(); i += slicing_group) { // subspan can correctly handel the last group, which may be smaller than // `slicing_group`. grouped_instructions.push_back( slice_starting_instructions.subspan(i, slicing_group)); } } for (const auto& grouped_slice_starting_instructions : grouped_instructions) { // Forward slicing. SliceOutput forward_slice_output; if (slicing_configuration.forward_slicing == SlicingConfiguration::ForwardSlicingConfig::kRoot) { // Slice to the root instruction of the entry computation of `hlo_module`. forward_slice_output = SliceModule( hlo_module, grouped_slice_starting_instructions, /*frontier_selector=*/nullptr, /*ignore_control_dependency=*/false, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/false); } else if (slicing_configuration.forward_slicing == SlicingConfiguration::ForwardSlicingConfig::kNca) { // slice to the nearest common ancestors of // `grouped_slice_starting_instructions` forward_slice_output = SliceModule( hlo_module, grouped_slice_starting_instructions, /*frontier_selector=*/nullptr, /*ignore_control_dependency=*/false, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/true); } VLOG(1) << "[Num of forward sliced insts]: " << forward_slice_output.NumSlicedInstructions(); // Backward slicing. SliceOutput backward_slice_output; if (slicing_configuration.backward_slicing) { backward_slice_output = SliceModule( hlo_module, grouped_slice_starting_instructions, /*frontier_selector=*/nullptr, /*ignore_control_dependency=*/false, /*forward_slice=*/false); } else { // Return the empty SliceOutput if backward slicing is not enabled. backward_slice_output = SliceOutput(); } // Combine forward slicing output and backward slicing output. auto sliced_result = SliceOutput(SliceOutput::UnionSlicedInstructions( forward_slice_output, backward_slice_output)); // Decide Root to start extraction based on `forward_slicing_config`. const HloInstruction* extraction_root = slicing_configuration.forward_slicing == SlicingConfiguration::ForwardSlicingConfig::kNca ? forward_slice_output.nearest_common_ancestor_root() : hlo_module->entry_computation()->root_instruction(); VLOG(1) << "[Root instruction of the sliced module]: " << extraction_root->ToString(); // Exclude the instructions that are not in the slicing results. auto extract_selector = [&sliced_result](const HloInstruction* hlo_inst) { for (const auto& [computation, instructions] : sliced_result.sliced_instructions()) { if (instructions.contains(hlo_inst)) { return true; } } return false; }; // Replace the excluded instructions in the entry computation with zeros. auto replace_type_selector = [](const HloInstruction* hlo_inst) -> ReplaceType { return ReplaceType::kReplaceZeroBroadcast; }; // Extract from the original module. auto extracted_module = ExtractModule(/*instruction=*/extraction_root, /*height=*/-1, /*extract_selector=*/extract_selector, /*replace_type_selector=*/replace_type_selector, /*cross_computation=*/true); // Remove the custom-call to sharding if `remove_sharding` is specified. if (slicing_configuration.remove_sharding) { RemoveSharding(extracted_module.get()); } // Reduce the parameter instructions of tuple shape if // `reduce_tuple_parameter` is specified. if (slicing_configuration.reduce_tuple_parameter) { ReduceTupleParameter(extracted_module.get()); } // Verify if the extracted module (after processing) is valid or not. HloVerifier verifier(/*layout_sensitive=*/false, /*allow_mixed_precision=*/true); TF_CHECK_OK(verifier.Run(extracted_module.get()).status()); sliced_modules.emplace_back(std::move(extracted_module)); } // Return all the sliced modules. CHECK_EQ(sliced_modules.size(), grouped_instructions.size()); return sliced_modules; } VLOG(1) << "[Num of forward sliced insts]: " VLOG(1) << "[Root instruction of the sliced module]: " auto extract_selector = [&sliced_result](const HloInstruction* hlo_inst) { for (const auto& [computation, instructions] : sliced_result.sliced_instructions()) { if (instructions.contains(hlo_inst)) { return true; } } return false; };
#include "xla/tools/hlo_slicer.h" #include <memory> #include <string> #include <utility> #include <vector> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/log/check.h" #include "absl/types/span.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/tests/hlo_test_base.h" #include "tsl/platform/statusor.h" TEST_F(HloSlicerTest, ForwardSlicingNearestCommonAncestor) { const std::string& hlo_string = R"( HloModule module ENTRY computation { p.0 = f32[10] parameter(0) p.1 = f32[10] parameter(1) add.0 = f32[10] add(p.0, p.1) p.2 = f32[10] parameter(2) mul.0 = f32[10] multiply(p.1, p.2) sub.0 = f32[10] subtract(add.0, mul.0) add.1 = f32[10] add(add.0, p.2) ROOT add.2 = f32[10] add(sub.0, add.1) } )"; TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> hlo_module, ParseAndReturnVerifiedModule(hlo_string)); auto p0 = FindInstruction(hlo_module.get(), "p.0"); auto p2 = FindInstruction(hlo_module.get(), "p.2"); auto mul0 = FindInstruction(hlo_module.get(), "mul.0"); auto add0 = FindInstruction(hlo_module.get(), "add.0"); auto sub0 = FindInstruction(hlo_module.get(), "sub.0"); auto add1 = FindInstruction(hlo_module.get(), "add.1"); const HloComputation* computation = hlo_module->entry_computation(); { std::vector<const HloInstruction*> relevant_instructions({p0}); auto sliced_result = SliceModule(hlo_module.get(), absl::MakeSpan(relevant_instructions), /*frontier_selector=*/nullptr, /*ignore_control_dependency=*/false, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/true); EXPECT_NE(sliced_result.nearest_common_ancestor_root(), nullptr); EXPECT_EQ(sliced_result.nearest_common_ancestor_root(), p0); EXPECT_EQ(sliced_result.NumSlicedInstructions(), 1); } { std::vector<const HloInstruction*> relevant_instructions({p0, p2}); auto sliced_result = SliceModule(hlo_module.get(), absl::MakeSpan(relevant_instructions), /*frontier_selector=*/nullptr, /*ignore_control_dependency=*/false, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/true); EXPECT_NE(sliced_result.nearest_common_ancestor_root(), nullptr); EXPECT_TRUE(sliced_result.nearest_common_ancestor_root() == sub0 || sliced_result.nearest_common_ancestor_root() == add1); EXPECT_TRUE(sliced_result.sliced_instructions().contains(computation)); auto sliced_instructions = sliced_result.sliced_instructions(); EXPECT_TRUE(sliced_instructions[computation].contains(add0)); } { std::vector<const HloInstruction*> relevant_instructions({p0, mul0}); auto sliced_result = SliceModule(hlo_module.get(), absl::MakeSpan(relevant_instructions), /*frontier_selector=*/nullptr, /*ignore_control_dependency=*/false, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/true); EXPECT_NE(sliced_result.nearest_common_ancestor_root(), nullptr); EXPECT_EQ(sliced_result.nearest_common_ancestor_root(), sub0); EXPECT_EQ(sliced_result.NumSlicedInstructions(), 4); EXPECT_TRUE(sliced_result.sliced_instructions().contains(computation)); auto sliced_instructions = sliced_result.sliced_instructions(); EXPECT_TRUE(sliced_instructions[computation].contains(p0)); EXPECT_TRUE(sliced_instructions[computation].contains(add0)); EXPECT_TRUE(sliced_instructions[computation].contains(mul0)); EXPECT_TRUE(sliced_instructions[computation].contains(sub0)); } }
HloSlicerTest_MultipleComputationBackwardSliceAndFrontier
xla/tools/hlo_slicer_test.cc
void ReduceTupleParameterHelper(HloModule* hlo_module, HloInstruction* tuple_parameter) { // Only handle the case where all the uses are GetTupleElement. for (HloInstruction* user_inst : tuple_parameter->users()) { if (user_inst->opcode() != HloOpcode::kGetTupleElement) { return; } } VLOG(1) << "Parameter instruction to be reduced: " << tuple_parameter->ToString() << " shape size: " << tuple_parameter->shape().tuple_shapes_size() << " users size: " << tuple_parameter->users().size(); // Collect the shapes of the elements that have users. std::vector<Shape> used_shapes; for (HloInstruction* user_inst : tuple_parameter->users()) { used_shapes.push_back(user_inst->shape()); } // Change the shape of `tuple_parameter` to only include the shape of elements // that have users. Shape new_tuple_shape = ShapeUtil::MakeTupleShape(absl::MakeSpan(used_shapes)); tuple_parameter->mutable_shape()->mutable_tuple_shapes()->clear(); for (const auto& shape : used_shapes) { tuple_parameter->mutable_shape()->mutable_tuple_shapes()->push_back(shape); } // Update the tuple index of all of the users of `tuple_parameter`, so that // they index into the right shape. for (int i = 0; i < tuple_parameter->users().size(); ++i) { tuple_parameter->users()[i]->set_tuple_index(i); } // Update HloModule shape. hlo_module->mutable_config().SetComputationLayoutIfExists( hlo_module->entry_computation()->ComputeProgramShape()); } VLOG(1) << "Parameter instruction to be reduced: " void ReduceTupleParameter(HloModule* hlo_module) { // Collect all the parameters instructions of tuple type. std::vector<HloInstruction*> tuple_parameters; for (HloInstruction* parameter : hlo_module->entry_computation()->parameter_instructions()) { if (parameter->shape().IsTuple()) { tuple_parameters.push_back(parameter); } } // For each parameter, invokes `ReduceTupleParameterHelper` to reduce its size // of dimensions. No instruction is added or removed from `hlo_module` during // this process, only shapes of parameter instructions and tuple indices of // their uses are updated. for (HloInstruction* tuple_parameter : tuple_parameters) { ReduceTupleParameterHelper(hlo_module, tuple_parameter); } } HloInstruction* FindShardingInstruction(HloModule* hlo_module) { for (HloComputation* computation : hlo_module->computations()) { for (HloInstruction* instruction : computation->instructions()) { if (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == "Sharding") { CHECK_EQ(instruction->operand_count(), 1); return instruction; } } } return nullptr; } void RemoveSharding(HloModule* hlo_module) { while (HloInstruction* custom_call_instruction = FindShardingInstruction(hlo_module)) { // Replace its uses with its operand. for (HloInstruction* user_instruction : custom_call_instruction->users()) { CHECK_OK(custom_call_instruction->ReplaceUseWith( user_instruction, custom_call_instruction->mutable_operand(0))); } // Detach the custom-call from computation. custom_call_instruction->DetachFromOperandsAndUsers(); CHECK_OK(custom_call_instruction->parent()->RemoveInstruction( custom_call_instruction)); VLOG(1) << "Removed sharding custom-call: " << custom_call_instruction->ToString(); // Verify if the module is still valid. HloVerifier verifier(/*layout_sensitive=*/false, /*allow_mixed_precision=*/true); TF_CHECK_OK(verifier.Run(hlo_module).status()); } } VLOG(1) << "Removed sharding custom-call: " void IntraComputationSlicing( const HloComputation* computation, absl::flat_hash_set<const HloInstruction*>& sliced_instructions, absl::flat_hash_set<const HloInstruction*>& frontier_instructions, bool forward_slice, FrontierSelector frontier_selector, bool ignore_control_dependency) { std::deque<const HloInstruction*> worklist(sliced_instructions.begin(), sliced_instructions.end()); while (!worklist.empty()) { const HloInstruction* inst = worklist.back(); worklist.pop_back(); // If `inst` is at the frontier, bookkeep it, and continue. if (frontier_selector && !frontier_selector(inst)) { frontier_instructions.insert(inst); continue; } // Initialize data-dependent instructions std::vector<HloInstruction*> instructions_to_propagate = forward_slice ? std::vector<HloInstruction*>(inst->users().begin(), inst->users().end()) : std::vector<HloInstruction*>(inst->operands().begin(), inst->operands().end()); // Append control-dependent instructions if necessary if (!ignore_control_dependency) { if (forward_slice) { instructions_to_propagate.insert(instructions_to_propagate.end(), inst->control_successors().begin(), inst->control_successors().end()); } else { instructions_to_propagate.insert(instructions_to_propagate.end(), inst->control_predecessors().begin(), inst->control_predecessors().end()); } } for (auto next_inst : instructions_to_propagate) { if (!sliced_instructions.contains(next_inst)) { worklist.push_front(next_inst); sliced_instructions.insert(next_inst); } } } } SliceOutput SliceModuleHelper( const HloModule* hlo_module, absl::Span<const HloInstruction*> slice_starting_instructions, FrontierSelector frontier_selector, bool ignore_control_dependency, bool forward_slice, bool nearest_common_ancestor_as_root) { // Initialize `sliced_computation_instructions_map`, which keeps track of all // the sliced instructions. absl::flat_hash_map<const HloComputation*, absl::flat_hash_set<const HloInstruction*>> sliced_computation_instructions_map; for (auto inst : slice_starting_instructions) { sliced_computation_instructions_map[inst->parent()].insert(inst); } // Initialize `frontier_computation_instructions_map`. absl::flat_hash_map<const HloComputation*, absl::flat_hash_set<const HloInstruction*>> frontier_computation_instructions_map; // Build call graph. std::unique_ptr<CallGraph> call_graph = CallGraph::Build(hlo_module); // Traverse computations in the post-order(forward slicing) or // reverse post-order(backward slicing) manner, and conduct intra-computation // slicing in that order. // // Post-order guarantees that when computation `a` is visited, all of its // callee computations have been visited, thus all the necessary propagation // to `a` has been conducted (i.e., the sliced caller instruction in `a` has // been marked, which serve as the starting point in // `IntraComputationSlicing`). // // Similarly, reverse post-order guarantees that when computation `a` is // visited, all of its caller computations have been visited, thus its root // instruction has been marked, which serve as the starting point in // `IntraComputationSlicing`. std::vector<HloComputation*> post_order_computations = hlo_module->MakeComputationPostOrder(); std::vector<HloComputation*> computations_to_traverse = forward_slice ? post_order_computations : std::vector<HloComputation*>(post_order_computations.rbegin(), post_order_computations.rend()); // If `nearest_common_ancestor_as_root` is enabled, we compute the // HloComputations that hold the `nearest_common_ancestor` instruction, which // are the stopping points when iterating through `computations_to_traverse`. absl::flat_hash_set<const HloComputation*> nearest_common_ancestor_computations; if (nearest_common_ancestor_as_root) { std::vector<const HloComputation*> starting_computations; for (const auto& [computation, instructions] : sliced_computation_instructions_map) { starting_computations.push_back(computation); } nearest_common_ancestor_computations = call_graph->NearestCommonAncestorComputations(starting_computations); CHECK(!nearest_common_ancestor_computations.empty()); } for (auto computation : computations_to_traverse) { if (sliced_computation_instructions_map.contains(computation)) { auto slicing_starting_instructions = std::vector<const HloInstruction*>( sliced_computation_instructions_map[computation].begin(), sliced_computation_instructions_map[computation].end()); // Do intra-computation slicing, starting from the instructions that has // been inserted in `sliced_computation_instructions_map[computation]`. IntraComputationSlicing( computation, sliced_computation_instructions_map[computation], frontier_computation_instructions_map[computation], forward_slice, frontier_selector, ignore_control_dependency); // The block below propagate the slicing results from the current visiting // computation to the next ones. if (forward_slice) { // Check if the current computation is one of the // `nearest_common_ancestor_computations`. If yes, we find the // `nearest_common_ancestor` as an instruction, and stop here. if (nearest_common_ancestor_as_root && nearest_common_ancestor_computations.contains(computation)) { // We use one of the nearest common ancestor instructions. const HloInstruction* nearest_common_ancestor_instruction = *(call_graph->NearestCommonAncestorInstructions( slicing_starting_instructions)) .begin(); CHECK_NE(nearest_common_ancestor_instruction, nullptr); return SliceOutput{sliced_computation_instructions_map, frontier_computation_instructions_map, nearest_common_ancestor_instruction}; } // Skip propagating if the ROOT instruction of the current computation // is NOT sliced. It is either because (1) the sliced instructions are // actually dead code or (2) `frontier_selector` finds frontier and stop // propagation. The found frontier could be at the root instruction, and // in this case, we stop propagation. if (!sliced_computation_instructions_map[computation].contains( computation->root_instruction()) || frontier_computation_instructions_map[computation].contains( computation->root_instruction())) { continue; } // Continue propagating to successors of the current computation, by // inserting its caller computation into // `sliced_computation_instructions_map`, and inserting the caller // instructions as the starting points for intra-computation slicing. for (auto caller_inst : call_graph->GetComputationCallers(computation)) { sliced_computation_instructions_map[caller_inst->parent()].insert( caller_inst); } } if (!forward_slice) { // Propagate to the callee computation of the current computation // that the sliced instructions invoke, by inserting its callee // computation into `sliced_computation_instructions_map`, and inserting // the root instruction of the callee computation as the starting points // for later intra-computation slicing. for (const auto& callsite : call_graph->GetNode(computation).callsites()) { if (sliced_computation_instructions_map[computation].contains( callsite.instruction())) { for (auto callee : callsite.called_computations()) { sliced_computation_instructions_map[callee].insert( callee->root_instruction()); } } } } } } return SliceOutput{sliced_computation_instructions_map, frontier_computation_instructions_map}; } SliceOutput SliceModule( const HloModule* hlo_module, absl::Span<const HloInstruction*> slice_starting_instructions, FrontierSelector frontier_selector, bool ignore_control_dependency, bool forward_slice, bool nearest_common_ancestor_as_root) { if (forward_slice) { if (!nearest_common_ancestor_as_root) { // Forward slicing with the original root as the root. return SliceModuleHelper(hlo_module, slice_starting_instructions, frontier_selector, ignore_control_dependency, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/false); } else { // Forward slicing with the nearest common ancestor (NCA) as the root. // // Internally, this feature is implemented by the following two steps: // 1. Conducting a pass of forward slicing and looking for the NCA // instruction. We first compute the "NCA computation", which is the // NCA, of the computations that hold the // `slice_starting_instructions`. This computation is achieved by // invoking "NearestCommonAncestorComputations" in the call graph. // Then, when we reach the "NCA computation", we compute the NCA of // the instructions that calls the computations which are on the path // from the `slice_starting_instructions` to this NCA computation. // 2. The slice from step 1 contains some redundant instructions, // because, when we do forward slicing, we do not know the exact path // to the NCA, and there could some nodes that cannot be reached from // the NCA. Therefore, in this step, we conduct a pass of backward // slicing from the NCA and filter out the redundant instructions, by // taking the intersection between the backward slicing results and // the forward slicing results from step 1. // Sanity check. CHECK(forward_slice) << "Option `nearest_common_ancestor_as_root` can " "only be enabled when " "forward slicing"; CHECK((frontier_selector == nullptr)) << "Option `nearest_common_ancestor_as_root` can not be specified " "with `frontier_selector`"; // Forward slicing to identify nearest common ancestor SliceOutput forward_slice_output = SliceModuleHelper(hlo_module, slice_starting_instructions, /*frontier_selector=*/nullptr, ignore_control_dependency, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/true); std::vector<const HloInstruction*> nearest_common_ancestor( {forward_slice_output.nearest_common_ancestor_root()}); CHECK_EQ(nearest_common_ancestor.size(), 1); // Backward slicing from the nearest common ancestor to filter out // the redundant computations/instructions in the sliced result in step 1. SliceOutput backward_slice_output = SliceModuleHelper(hlo_module, /*slice_starting_instructions=*/ absl::MakeSpan(nearest_common_ancestor), /*frontier_selector=*/nullptr, ignore_control_dependency, /*forward_slice=*/false, /*nearest_common_ancestor_as_root=*/false); // Intersect the sliced instructions between forward slicing pass and // backward slicing pass as the new sliced instructions, and return the // new SliceOutput. return SliceOutput{SliceOutput::IntersectSlicedInstructions( forward_slice_output, backward_slice_output), backward_slice_output.frontier_instructions(), forward_slice_output.nearest_common_ancestor_root()}; } } else { // Backward slicing. return SliceModuleHelper(hlo_module, slice_starting_instructions, frontier_selector, ignore_control_dependency, /*forward_slice=*/false, /*nearest_common_ancestor_as_root=*/false); } } std::vector<std::unique_ptr<HloModule>> SliceModuleAndExtract( const HloModule* hlo_module, absl::Span<const HloInstruction*> slice_starting_instructions, const SlicingConfiguration& slicing_configuration) { std::vector<std::unique_ptr<HloModule>> sliced_modules; // Group `slice_starting_instructions` based on `slicing_group` configuration. int slicing_group = slicing_configuration.slicing_group; CHECK(slicing_group >= 1 || slicing_group == -1); std::vector<absl::Span<const HloInstruction*>> grouped_instructions; if (slicing_group == -1) { grouped_instructions = {slice_starting_instructions}; } else { for (int i = 0; i < slice_starting_instructions.size(); i += slicing_group) { // subspan can correctly handel the last group, which may be smaller than // `slicing_group`. grouped_instructions.push_back( slice_starting_instructions.subspan(i, slicing_group)); } } for (const auto& grouped_slice_starting_instructions : grouped_instructions) { // Forward slicing. SliceOutput forward_slice_output; if (slicing_configuration.forward_slicing == SlicingConfiguration::ForwardSlicingConfig::kRoot) { // Slice to the root instruction of the entry computation of `hlo_module`. forward_slice_output = SliceModule( hlo_module, grouped_slice_starting_instructions, /*frontier_selector=*/nullptr, /*ignore_control_dependency=*/false, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/false); } else if (slicing_configuration.forward_slicing == SlicingConfiguration::ForwardSlicingConfig::kNca) { // slice to the nearest common ancestors of // `grouped_slice_starting_instructions` forward_slice_output = SliceModule( hlo_module, grouped_slice_starting_instructions, /*frontier_selector=*/nullptr, /*ignore_control_dependency=*/false, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/true); } VLOG(1) << "[Num of forward sliced insts]: " << forward_slice_output.NumSlicedInstructions(); // Backward slicing. SliceOutput backward_slice_output; if (slicing_configuration.backward_slicing) { backward_slice_output = SliceModule( hlo_module, grouped_slice_starting_instructions, /*frontier_selector=*/nullptr, /*ignore_control_dependency=*/false, /*forward_slice=*/false); } else { // Return the empty SliceOutput if backward slicing is not enabled. backward_slice_output = SliceOutput(); } // Combine forward slicing output and backward slicing output. auto sliced_result = SliceOutput(SliceOutput::UnionSlicedInstructions( forward_slice_output, backward_slice_output)); // Decide Root to start extraction based on `forward_slicing_config`. const HloInstruction* extraction_root = slicing_configuration.forward_slicing == SlicingConfiguration::ForwardSlicingConfig::kNca ? forward_slice_output.nearest_common_ancestor_root() : hlo_module->entry_computation()->root_instruction(); VLOG(1) << "[Root instruction of the sliced module]: " << extraction_root->ToString(); // Exclude the instructions that are not in the slicing results. auto extract_selector = [&sliced_result](const HloInstruction* hlo_inst) { for (const auto& [computation, instructions] : sliced_result.sliced_instructions()) { if (instructions.contains(hlo_inst)) { return true; } } return false; }; // Replace the excluded instructions in the entry computation with zeros. auto replace_type_selector = [](const HloInstruction* hlo_inst) -> ReplaceType { return ReplaceType::kReplaceZeroBroadcast; }; // Extract from the original module. auto extracted_module = ExtractModule(/*instruction=*/extraction_root, /*height=*/-1, /*extract_selector=*/extract_selector, /*replace_type_selector=*/replace_type_selector, /*cross_computation=*/true); // Remove the custom-call to sharding if `remove_sharding` is specified. if (slicing_configuration.remove_sharding) { RemoveSharding(extracted_module.get()); } // Reduce the parameter instructions of tuple shape if // `reduce_tuple_parameter` is specified. if (slicing_configuration.reduce_tuple_parameter) { ReduceTupleParameter(extracted_module.get()); } // Verify if the extracted module (after processing) is valid or not. HloVerifier verifier(/*layout_sensitive=*/false, /*allow_mixed_precision=*/true); TF_CHECK_OK(verifier.Run(extracted_module.get()).status()); sliced_modules.emplace_back(std::move(extracted_module)); } // Return all the sliced modules. CHECK_EQ(sliced_modules.size(), grouped_instructions.size()); return sliced_modules; } VLOG(1) << "[Num of forward sliced insts]: " VLOG(1) << "[Root instruction of the sliced module]: " auto extract_selector = [&sliced_result](const HloInstruction* hlo_inst) { for (const auto& [computation, instructions] : sliced_result.sliced_instructions()) { if (instructions.contains(hlo_inst)) { return true; } } return false; };
#include "xla/tools/hlo_slicer.h" #include <memory> #include <string> #include <utility> #include <vector> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/log/check.h" #include "absl/types/span.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/tests/hlo_test_base.h" #include "tsl/platform/statusor.h" TEST_F(HloSlicerTest, MultipleComputationBackwardSliceAndFrontier) { const std::string& hlo_string = R"( HloModule axpy_module calculate_alpha { c.0 = f32[] constant(1) c.1 = f32[] constant(2) c.2 = f32[] add(c.0, c.1) c.3 = f32[] constant(4) ROOT ret = f32[] multiply(c.2, c.3) } ENTRY axpy_computation { p.0 = f32[] parameter(0) alpha = f32[] call(), to_apply=calculate_alpha ROOT add = f32[] add(p.0, alpha) } )"; TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> hlo_module, ParseAndReturnVerifiedModule(hlo_string)); auto entry_comp = FindComputation(hlo_module.get(), "axpy_computation"); EXPECT_NE(entry_comp, nullptr); auto calculate_alpha_comp = FindComputation(hlo_module.get(), "calculate_alpha"); EXPECT_NE(calculate_alpha_comp, nullptr); auto ret = FindInstruction(hlo_module.get(), "ret"); EXPECT_THAT(ret, op::Multiply()); auto c0 = FindInstruction(hlo_module.get(), "c.0"); EXPECT_THAT(c0, op::Constant()); auto c1 = FindInstruction(hlo_module.get(), "c.1"); EXPECT_THAT(c1, op::Constant()); auto c2 = FindInstruction(hlo_module.get(), "c.2"); EXPECT_THAT(c2, op::Add()); auto c3 = FindInstruction(hlo_module.get(), "c.3"); EXPECT_THAT(c3, op::Constant()); auto alpha = FindInstruction(hlo_module.get(), "alpha"); EXPECT_THAT(alpha, op::Call()); { auto hlo_selector = [](const HloInstruction* hlo_inst) -> bool { return true; }; std::vector<const HloInstruction*> relevant_instructions({c2}); auto sliced_result = SliceModule( hlo_module.get(), absl::MakeSpan(relevant_instructions), hlo_selector, /*ignore_control_dependency=*/false, /*forward_slice=*/false); auto sliced_instructions = sliced_result.sliced_instructions(); EXPECT_EQ(sliced_result.NumSlicedInstructions(), 3); EXPECT_EQ(sliced_instructions.size(), 1); EXPECT_TRUE(sliced_instructions.contains(calculate_alpha_comp)); EXPECT_EQ(sliced_instructions[calculate_alpha_comp].size(), 3); EXPECT_TRUE(sliced_instructions[calculate_alpha_comp].contains(c0)); EXPECT_TRUE(sliced_instructions[calculate_alpha_comp].contains(c1)); EXPECT_TRUE(sliced_instructions[calculate_alpha_comp].contains(c2)); EXPECT_EQ(sliced_result.NumFrontierInstructions(), 0); } { auto hlo_selector = [](const HloInstruction* hlo_inst) -> bool { return true; }; std::vector<const HloInstruction*> relevant_instructions({alpha}); auto sliced_result = SliceModule( hlo_module.get(), absl::MakeSpan(relevant_instructions), hlo_selector, /*ignore_control_dependency=*/false, /*forward_slice=*/false); auto sliced_instructions = sliced_result.sliced_instructions(); EXPECT_EQ(sliced_instructions.size(), 2); EXPECT_TRUE(sliced_instructions.contains(calculate_alpha_comp)); EXPECT_EQ(sliced_instructions[calculate_alpha_comp].size(), 5); EXPECT_TRUE(sliced_instructions[calculate_alpha_comp].contains(c0)); EXPECT_TRUE(sliced_instructions[calculate_alpha_comp].contains(c1)); EXPECT_TRUE(sliced_instructions[calculate_alpha_comp].contains(c2)); EXPECT_TRUE(sliced_instructions[calculate_alpha_comp].contains(c3)); EXPECT_TRUE(sliced_instructions[calculate_alpha_comp].contains(ret)); EXPECT_TRUE(sliced_instructions.contains(entry_comp)); EXPECT_EQ(sliced_instructions[entry_comp].size(), 1); EXPECT_TRUE(sliced_instructions[entry_comp].contains(alpha)); EXPECT_EQ(sliced_result.NumFrontierInstructions(), 0); } // Testing backward slicing frontier. { auto add_slicer = [](const HloInstruction* hlo_inst) -> bool { return hlo_inst->opcode() != HloOpcode::kAdd; }; std::vector<const HloInstruction*> relevant_instructions({ret}); auto sliced_result = SliceModule( hlo_module.get(), absl::MakeSpan(relevant_instructions), add_slicer, /*ignore_control_dependency=*/false, /*forward_slice=*/false); auto sliced_instructions = sliced_result.sliced_instructions(); EXPECT_EQ(sliced_result.NumSlicedInstructions(), 3); EXPECT_EQ(sliced_instructions.size(), 1); EXPECT_TRUE(sliced_instructions.contains(calculate_alpha_comp)); EXPECT_EQ(sliced_instructions[calculate_alpha_comp].size(), 3); EXPECT_TRUE(sliced_instructions[calculate_alpha_comp].contains(ret)); EXPECT_TRUE(sliced_instructions[calculate_alpha_comp].contains(c3)); EXPECT_TRUE(sliced_instructions[calculate_alpha_comp].contains(c2)); EXPECT_EQ(sliced_result.NumFrontierInstructions(), 1); auto frontier_instructions = sliced_result.frontier_instructions(); EXPECT_TRUE(frontier_instructions.contains(calculate_alpha_comp)); EXPECT_TRUE(frontier_instructions[calculate_alpha_comp].contains(c2)); } { auto mul_slicer = [](const HloInstruction* hlo_inst) -> bool { return hlo_inst->opcode() != HloOpcode::kMultiply; }; std::vector<const HloInstruction*> relevant_instructions({alpha}); auto sliced_result = SliceModule( hlo_module.get(), absl::MakeSpan(relevant_instructions), mul_slicer, /*ignore_control_dependency=*/false, /*forward_slice=*/false); auto sliced_instructions = sliced_result.sliced_instructions(); EXPECT_EQ(sliced_result.NumSlicedInstructions(), 2); EXPECT_EQ(sliced_instructions.size(), 2); EXPECT_TRUE(sliced_instructions.contains(calculate_alpha_comp)); EXPECT_EQ(sliced_instructions[calculate_alpha_comp].size(), 1); EXPECT_TRUE(sliced_instructions[calculate_alpha_comp].contains(ret)); EXPECT_TRUE(sliced_instructions.contains(entry_comp)); EXPECT_EQ(sliced_instructions[entry_comp].size(), 1); EXPECT_TRUE(sliced_instructions[entry_comp].contains(alpha)); EXPECT_EQ(sliced_result.NumFrontierInstructions(), 1); auto frontier_instructions = sliced_result.frontier_instructions(); EXPECT_TRUE(frontier_instructions.contains(calculate_alpha_comp)); EXPECT_TRUE(frontier_instructions[calculate_alpha_comp].contains(ret)); } }
HloSlicerTest_MultipleComputationForwardFrontier
xla/tools/hlo_slicer_test.cc
void ReduceTupleParameterHelper(HloModule* hlo_module, HloInstruction* tuple_parameter) { // Only handle the case where all the uses are GetTupleElement. for (HloInstruction* user_inst : tuple_parameter->users()) { if (user_inst->opcode() != HloOpcode::kGetTupleElement) { return; } } VLOG(1) << "Parameter instruction to be reduced: " << tuple_parameter->ToString() << " shape size: " << tuple_parameter->shape().tuple_shapes_size() << " users size: " << tuple_parameter->users().size(); // Collect the shapes of the elements that have users. std::vector<Shape> used_shapes; for (HloInstruction* user_inst : tuple_parameter->users()) { used_shapes.push_back(user_inst->shape()); } // Change the shape of `tuple_parameter` to only include the shape of elements // that have users. Shape new_tuple_shape = ShapeUtil::MakeTupleShape(absl::MakeSpan(used_shapes)); tuple_parameter->mutable_shape()->mutable_tuple_shapes()->clear(); for (const auto& shape : used_shapes) { tuple_parameter->mutable_shape()->mutable_tuple_shapes()->push_back(shape); } // Update the tuple index of all of the users of `tuple_parameter`, so that // they index into the right shape. for (int i = 0; i < tuple_parameter->users().size(); ++i) { tuple_parameter->users()[i]->set_tuple_index(i); } // Update HloModule shape. hlo_module->mutable_config().SetComputationLayoutIfExists( hlo_module->entry_computation()->ComputeProgramShape()); } VLOG(1) << "Parameter instruction to be reduced: " void ReduceTupleParameter(HloModule* hlo_module) { // Collect all the parameters instructions of tuple type. std::vector<HloInstruction*> tuple_parameters; for (HloInstruction* parameter : hlo_module->entry_computation()->parameter_instructions()) { if (parameter->shape().IsTuple()) { tuple_parameters.push_back(parameter); } } // For each parameter, invokes `ReduceTupleParameterHelper` to reduce its size // of dimensions. No instruction is added or removed from `hlo_module` during // this process, only shapes of parameter instructions and tuple indices of // their uses are updated. for (HloInstruction* tuple_parameter : tuple_parameters) { ReduceTupleParameterHelper(hlo_module, tuple_parameter); } } HloInstruction* FindShardingInstruction(HloModule* hlo_module) { for (HloComputation* computation : hlo_module->computations()) { for (HloInstruction* instruction : computation->instructions()) { if (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == "Sharding") { CHECK_EQ(instruction->operand_count(), 1); return instruction; } } } return nullptr; } void RemoveSharding(HloModule* hlo_module) { while (HloInstruction* custom_call_instruction = FindShardingInstruction(hlo_module)) { // Replace its uses with its operand. for (HloInstruction* user_instruction : custom_call_instruction->users()) { CHECK_OK(custom_call_instruction->ReplaceUseWith( user_instruction, custom_call_instruction->mutable_operand(0))); } // Detach the custom-call from computation. custom_call_instruction->DetachFromOperandsAndUsers(); CHECK_OK(custom_call_instruction->parent()->RemoveInstruction( custom_call_instruction)); VLOG(1) << "Removed sharding custom-call: " << custom_call_instruction->ToString(); // Verify if the module is still valid. HloVerifier verifier(/*layout_sensitive=*/false, /*allow_mixed_precision=*/true); TF_CHECK_OK(verifier.Run(hlo_module).status()); } } VLOG(1) << "Removed sharding custom-call: " void IntraComputationSlicing( const HloComputation* computation, absl::flat_hash_set<const HloInstruction*>& sliced_instructions, absl::flat_hash_set<const HloInstruction*>& frontier_instructions, bool forward_slice, FrontierSelector frontier_selector, bool ignore_control_dependency) { std::deque<const HloInstruction*> worklist(sliced_instructions.begin(), sliced_instructions.end()); while (!worklist.empty()) { const HloInstruction* inst = worklist.back(); worklist.pop_back(); // If `inst` is at the frontier, bookkeep it, and continue. if (frontier_selector && !frontier_selector(inst)) { frontier_instructions.insert(inst); continue; } // Initialize data-dependent instructions std::vector<HloInstruction*> instructions_to_propagate = forward_slice ? std::vector<HloInstruction*>(inst->users().begin(), inst->users().end()) : std::vector<HloInstruction*>(inst->operands().begin(), inst->operands().end()); // Append control-dependent instructions if necessary if (!ignore_control_dependency) { if (forward_slice) { instructions_to_propagate.insert(instructions_to_propagate.end(), inst->control_successors().begin(), inst->control_successors().end()); } else { instructions_to_propagate.insert(instructions_to_propagate.end(), inst->control_predecessors().begin(), inst->control_predecessors().end()); } } for (auto next_inst : instructions_to_propagate) { if (!sliced_instructions.contains(next_inst)) { worklist.push_front(next_inst); sliced_instructions.insert(next_inst); } } } } SliceOutput SliceModuleHelper( const HloModule* hlo_module, absl::Span<const HloInstruction*> slice_starting_instructions, FrontierSelector frontier_selector, bool ignore_control_dependency, bool forward_slice, bool nearest_common_ancestor_as_root) { // Initialize `sliced_computation_instructions_map`, which keeps track of all // the sliced instructions. absl::flat_hash_map<const HloComputation*, absl::flat_hash_set<const HloInstruction*>> sliced_computation_instructions_map; for (auto inst : slice_starting_instructions) { sliced_computation_instructions_map[inst->parent()].insert(inst); } // Initialize `frontier_computation_instructions_map`. absl::flat_hash_map<const HloComputation*, absl::flat_hash_set<const HloInstruction*>> frontier_computation_instructions_map; // Build call graph. std::unique_ptr<CallGraph> call_graph = CallGraph::Build(hlo_module); // Traverse computations in the post-order(forward slicing) or // reverse post-order(backward slicing) manner, and conduct intra-computation // slicing in that order. // // Post-order guarantees that when computation `a` is visited, all of its // callee computations have been visited, thus all the necessary propagation // to `a` has been conducted (i.e., the sliced caller instruction in `a` has // been marked, which serve as the starting point in // `IntraComputationSlicing`). // // Similarly, reverse post-order guarantees that when computation `a` is // visited, all of its caller computations have been visited, thus its root // instruction has been marked, which serve as the starting point in // `IntraComputationSlicing`. std::vector<HloComputation*> post_order_computations = hlo_module->MakeComputationPostOrder(); std::vector<HloComputation*> computations_to_traverse = forward_slice ? post_order_computations : std::vector<HloComputation*>(post_order_computations.rbegin(), post_order_computations.rend()); // If `nearest_common_ancestor_as_root` is enabled, we compute the // HloComputations that hold the `nearest_common_ancestor` instruction, which // are the stopping points when iterating through `computations_to_traverse`. absl::flat_hash_set<const HloComputation*> nearest_common_ancestor_computations; if (nearest_common_ancestor_as_root) { std::vector<const HloComputation*> starting_computations; for (const auto& [computation, instructions] : sliced_computation_instructions_map) { starting_computations.push_back(computation); } nearest_common_ancestor_computations = call_graph->NearestCommonAncestorComputations(starting_computations); CHECK(!nearest_common_ancestor_computations.empty()); } for (auto computation : computations_to_traverse) { if (sliced_computation_instructions_map.contains(computation)) { auto slicing_starting_instructions = std::vector<const HloInstruction*>( sliced_computation_instructions_map[computation].begin(), sliced_computation_instructions_map[computation].end()); // Do intra-computation slicing, starting from the instructions that has // been inserted in `sliced_computation_instructions_map[computation]`. IntraComputationSlicing( computation, sliced_computation_instructions_map[computation], frontier_computation_instructions_map[computation], forward_slice, frontier_selector, ignore_control_dependency); // The block below propagate the slicing results from the current visiting // computation to the next ones. if (forward_slice) { // Check if the current computation is one of the // `nearest_common_ancestor_computations`. If yes, we find the // `nearest_common_ancestor` as an instruction, and stop here. if (nearest_common_ancestor_as_root && nearest_common_ancestor_computations.contains(computation)) { // We use one of the nearest common ancestor instructions. const HloInstruction* nearest_common_ancestor_instruction = *(call_graph->NearestCommonAncestorInstructions( slicing_starting_instructions)) .begin(); CHECK_NE(nearest_common_ancestor_instruction, nullptr); return SliceOutput{sliced_computation_instructions_map, frontier_computation_instructions_map, nearest_common_ancestor_instruction}; } // Skip propagating if the ROOT instruction of the current computation // is NOT sliced. It is either because (1) the sliced instructions are // actually dead code or (2) `frontier_selector` finds frontier and stop // propagation. The found frontier could be at the root instruction, and // in this case, we stop propagation. if (!sliced_computation_instructions_map[computation].contains( computation->root_instruction()) || frontier_computation_instructions_map[computation].contains( computation->root_instruction())) { continue; } // Continue propagating to successors of the current computation, by // inserting its caller computation into // `sliced_computation_instructions_map`, and inserting the caller // instructions as the starting points for intra-computation slicing. for (auto caller_inst : call_graph->GetComputationCallers(computation)) { sliced_computation_instructions_map[caller_inst->parent()].insert( caller_inst); } } if (!forward_slice) { // Propagate to the callee computation of the current computation // that the sliced instructions invoke, by inserting its callee // computation into `sliced_computation_instructions_map`, and inserting // the root instruction of the callee computation as the starting points // for later intra-computation slicing. for (const auto& callsite : call_graph->GetNode(computation).callsites()) { if (sliced_computation_instructions_map[computation].contains( callsite.instruction())) { for (auto callee : callsite.called_computations()) { sliced_computation_instructions_map[callee].insert( callee->root_instruction()); } } } } } } return SliceOutput{sliced_computation_instructions_map, frontier_computation_instructions_map}; } SliceOutput SliceModule( const HloModule* hlo_module, absl::Span<const HloInstruction*> slice_starting_instructions, FrontierSelector frontier_selector, bool ignore_control_dependency, bool forward_slice, bool nearest_common_ancestor_as_root) { if (forward_slice) { if (!nearest_common_ancestor_as_root) { // Forward slicing with the original root as the root. return SliceModuleHelper(hlo_module, slice_starting_instructions, frontier_selector, ignore_control_dependency, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/false); } else { // Forward slicing with the nearest common ancestor (NCA) as the root. // // Internally, this feature is implemented by the following two steps: // 1. Conducting a pass of forward slicing and looking for the NCA // instruction. We first compute the "NCA computation", which is the // NCA, of the computations that hold the // `slice_starting_instructions`. This computation is achieved by // invoking "NearestCommonAncestorComputations" in the call graph. // Then, when we reach the "NCA computation", we compute the NCA of // the instructions that calls the computations which are on the path // from the `slice_starting_instructions` to this NCA computation. // 2. The slice from step 1 contains some redundant instructions, // because, when we do forward slicing, we do not know the exact path // to the NCA, and there could some nodes that cannot be reached from // the NCA. Therefore, in this step, we conduct a pass of backward // slicing from the NCA and filter out the redundant instructions, by // taking the intersection between the backward slicing results and // the forward slicing results from step 1. // Sanity check. CHECK(forward_slice) << "Option `nearest_common_ancestor_as_root` can " "only be enabled when " "forward slicing"; CHECK((frontier_selector == nullptr)) << "Option `nearest_common_ancestor_as_root` can not be specified " "with `frontier_selector`"; // Forward slicing to identify nearest common ancestor SliceOutput forward_slice_output = SliceModuleHelper(hlo_module, slice_starting_instructions, /*frontier_selector=*/nullptr, ignore_control_dependency, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/true); std::vector<const HloInstruction*> nearest_common_ancestor( {forward_slice_output.nearest_common_ancestor_root()}); CHECK_EQ(nearest_common_ancestor.size(), 1); // Backward slicing from the nearest common ancestor to filter out // the redundant computations/instructions in the sliced result in step 1. SliceOutput backward_slice_output = SliceModuleHelper(hlo_module, /*slice_starting_instructions=*/ absl::MakeSpan(nearest_common_ancestor), /*frontier_selector=*/nullptr, ignore_control_dependency, /*forward_slice=*/false, /*nearest_common_ancestor_as_root=*/false); // Intersect the sliced instructions between forward slicing pass and // backward slicing pass as the new sliced instructions, and return the // new SliceOutput. return SliceOutput{SliceOutput::IntersectSlicedInstructions( forward_slice_output, backward_slice_output), backward_slice_output.frontier_instructions(), forward_slice_output.nearest_common_ancestor_root()}; } } else { // Backward slicing. return SliceModuleHelper(hlo_module, slice_starting_instructions, frontier_selector, ignore_control_dependency, /*forward_slice=*/false, /*nearest_common_ancestor_as_root=*/false); } } std::vector<std::unique_ptr<HloModule>> SliceModuleAndExtract( const HloModule* hlo_module, absl::Span<const HloInstruction*> slice_starting_instructions, const SlicingConfiguration& slicing_configuration) { std::vector<std::unique_ptr<HloModule>> sliced_modules; // Group `slice_starting_instructions` based on `slicing_group` configuration. int slicing_group = slicing_configuration.slicing_group; CHECK(slicing_group >= 1 || slicing_group == -1); std::vector<absl::Span<const HloInstruction*>> grouped_instructions; if (slicing_group == -1) { grouped_instructions = {slice_starting_instructions}; } else { for (int i = 0; i < slice_starting_instructions.size(); i += slicing_group) { // subspan can correctly handel the last group, which may be smaller than // `slicing_group`. grouped_instructions.push_back( slice_starting_instructions.subspan(i, slicing_group)); } } for (const auto& grouped_slice_starting_instructions : grouped_instructions) { // Forward slicing. SliceOutput forward_slice_output; if (slicing_configuration.forward_slicing == SlicingConfiguration::ForwardSlicingConfig::kRoot) { // Slice to the root instruction of the entry computation of `hlo_module`. forward_slice_output = SliceModule( hlo_module, grouped_slice_starting_instructions, /*frontier_selector=*/nullptr, /*ignore_control_dependency=*/false, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/false); } else if (slicing_configuration.forward_slicing == SlicingConfiguration::ForwardSlicingConfig::kNca) { // slice to the nearest common ancestors of // `grouped_slice_starting_instructions` forward_slice_output = SliceModule( hlo_module, grouped_slice_starting_instructions, /*frontier_selector=*/nullptr, /*ignore_control_dependency=*/false, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/true); } VLOG(1) << "[Num of forward sliced insts]: " << forward_slice_output.NumSlicedInstructions(); // Backward slicing. SliceOutput backward_slice_output; if (slicing_configuration.backward_slicing) { backward_slice_output = SliceModule( hlo_module, grouped_slice_starting_instructions, /*frontier_selector=*/nullptr, /*ignore_control_dependency=*/false, /*forward_slice=*/false); } else { // Return the empty SliceOutput if backward slicing is not enabled. backward_slice_output = SliceOutput(); } // Combine forward slicing output and backward slicing output. auto sliced_result = SliceOutput(SliceOutput::UnionSlicedInstructions( forward_slice_output, backward_slice_output)); // Decide Root to start extraction based on `forward_slicing_config`. const HloInstruction* extraction_root = slicing_configuration.forward_slicing == SlicingConfiguration::ForwardSlicingConfig::kNca ? forward_slice_output.nearest_common_ancestor_root() : hlo_module->entry_computation()->root_instruction(); VLOG(1) << "[Root instruction of the sliced module]: " << extraction_root->ToString(); // Exclude the instructions that are not in the slicing results. auto extract_selector = [&sliced_result](const HloInstruction* hlo_inst) { for (const auto& [computation, instructions] : sliced_result.sliced_instructions()) { if (instructions.contains(hlo_inst)) { return true; } } return false; }; // Replace the excluded instructions in the entry computation with zeros. auto replace_type_selector = [](const HloInstruction* hlo_inst) -> ReplaceType { return ReplaceType::kReplaceZeroBroadcast; }; // Extract from the original module. auto extracted_module = ExtractModule(/*instruction=*/extraction_root, /*height=*/-1, /*extract_selector=*/extract_selector, /*replace_type_selector=*/replace_type_selector, /*cross_computation=*/true); // Remove the custom-call to sharding if `remove_sharding` is specified. if (slicing_configuration.remove_sharding) { RemoveSharding(extracted_module.get()); } // Reduce the parameter instructions of tuple shape if // `reduce_tuple_parameter` is specified. if (slicing_configuration.reduce_tuple_parameter) { ReduceTupleParameter(extracted_module.get()); } // Verify if the extracted module (after processing) is valid or not. HloVerifier verifier(/*layout_sensitive=*/false, /*allow_mixed_precision=*/true); TF_CHECK_OK(verifier.Run(extracted_module.get()).status()); sliced_modules.emplace_back(std::move(extracted_module)); } // Return all the sliced modules. CHECK_EQ(sliced_modules.size(), grouped_instructions.size()); return sliced_modules; } VLOG(1) << "[Num of forward sliced insts]: " VLOG(1) << "[Root instruction of the sliced module]: " auto extract_selector = [&sliced_result](const HloInstruction* hlo_inst) { for (const auto& [computation, instructions] : sliced_result.sliced_instructions()) { if (instructions.contains(hlo_inst)) { return true; } } return false; };
#include "xla/tools/hlo_slicer.h" #include <memory> #include <string> #include <utility> #include <vector> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/log/check.h" #include "absl/types/span.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/tests/hlo_test_base.h" #include "tsl/platform/statusor.h" TEST_F(HloSlicerTest, MultipleComputationForwardFrontier) { const std::string& hlo_string = R"( HloModule axpy_module calculate_alpha { c.0 = f32[] constant(1) c.1 = f32[] constant(2) c.2 = f32[] add(c.0, c.1) c.3 = f32[] constant(4) ROOT ret = f32[] multiply(c.2, c.3) } ENTRY axpy_computation { p.0 = f32[] parameter(0) alpha = f32[] call(), to_apply=calculate_alpha ROOT add = f32[] add(p.0, alpha) } )"; TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> hlo_module, ParseAndReturnVerifiedModule(hlo_string)); auto entry_comp = FindComputation(hlo_module.get(), "axpy_computation"); EXPECT_NE(entry_comp, nullptr); auto calculate_alpha_comp = FindComputation(hlo_module.get(), "calculate_alpha"); EXPECT_NE(calculate_alpha_comp, nullptr); auto ret = FindInstruction(hlo_module.get(), "ret"); EXPECT_THAT(ret, op::Multiply()); auto c2 = FindInstruction(hlo_module.get(), "c.2"); EXPECT_THAT(c2, op::Add()); auto c3 = FindInstruction(hlo_module.get(), "c.3"); EXPECT_THAT(c3, op::Constant()); auto alpha = FindInstruction(hlo_module.get(), "alpha"); EXPECT_THAT(alpha, op::Call()); // Frontier at the root instruction of a callee computation. { auto hlo_selector = [&ret](const HloInstruction* hlo_inst) -> bool { return hlo_inst != ret; }; std::vector<const HloInstruction*> relevant_instructions({c2}); auto sliced_result = SliceModule( hlo_module.get(), absl::MakeSpan(relevant_instructions), hlo_selector); auto sliced_instructions = sliced_result.sliced_instructions(); EXPECT_EQ(sliced_result.NumSlicedInstructions(), 2); EXPECT_EQ(sliced_instructions.size(), 1); EXPECT_TRUE(sliced_instructions.contains(calculate_alpha_comp)); EXPECT_EQ(sliced_instructions[calculate_alpha_comp].size(), 2); EXPECT_TRUE(sliced_instructions[calculate_alpha_comp].contains(c2)); EXPECT_TRUE(sliced_instructions[calculate_alpha_comp].contains(ret)); EXPECT_EQ(sliced_result.NumFrontierInstructions(), 1); auto frontier_instructions = sliced_result.frontier_instructions(); EXPECT_TRUE(frontier_instructions.contains(calculate_alpha_comp)); EXPECT_TRUE(frontier_instructions[calculate_alpha_comp].contains(ret)); } // Frontier at the callsite instruction. { auto hlo_selector = [](const HloInstruction* hlo_inst) -> bool { return hlo_inst->opcode() != HloOpcode::kCall; }; std::vector<const HloInstruction*> relevant_instructions({c2}); auto sliced_result = SliceModule( hlo_module.get(), absl::MakeSpan(relevant_instructions), hlo_selector); auto sliced_instructions = sliced_result.sliced_instructions(); EXPECT_EQ(sliced_instructions.size(), 2); EXPECT_TRUE(sliced_instructions.contains(calculate_alpha_comp)); EXPECT_EQ(sliced_instructions[calculate_alpha_comp].size(), 2); EXPECT_TRUE(sliced_instructions[calculate_alpha_comp].contains(c2)); EXPECT_TRUE(sliced_instructions[calculate_alpha_comp].contains(ret)); EXPECT_TRUE(sliced_instructions.contains(entry_comp)); EXPECT_EQ(sliced_instructions[entry_comp].size(), 1); EXPECT_TRUE(sliced_instructions[entry_comp].contains(alpha)); EXPECT_EQ(sliced_result.NumFrontierInstructions(), 1); auto frontier_instructions = sliced_result.frontier_instructions(); EXPECT_TRUE(frontier_instructions.contains(entry_comp)); EXPECT_TRUE(frontier_instructions[entry_comp].contains(alpha)); } }
HloSlicerTest_MultipleComputationForwardSlice
xla/tools/hlo_slicer_test.cc
void ReduceTupleParameterHelper(HloModule* hlo_module, HloInstruction* tuple_parameter) { // Only handle the case where all the uses are GetTupleElement. for (HloInstruction* user_inst : tuple_parameter->users()) { if (user_inst->opcode() != HloOpcode::kGetTupleElement) { return; } } VLOG(1) << "Parameter instruction to be reduced: " << tuple_parameter->ToString() << " shape size: " << tuple_parameter->shape().tuple_shapes_size() << " users size: " << tuple_parameter->users().size(); // Collect the shapes of the elements that have users. std::vector<Shape> used_shapes; for (HloInstruction* user_inst : tuple_parameter->users()) { used_shapes.push_back(user_inst->shape()); } // Change the shape of `tuple_parameter` to only include the shape of elements // that have users. Shape new_tuple_shape = ShapeUtil::MakeTupleShape(absl::MakeSpan(used_shapes)); tuple_parameter->mutable_shape()->mutable_tuple_shapes()->clear(); for (const auto& shape : used_shapes) { tuple_parameter->mutable_shape()->mutable_tuple_shapes()->push_back(shape); } // Update the tuple index of all of the users of `tuple_parameter`, so that // they index into the right shape. for (int i = 0; i < tuple_parameter->users().size(); ++i) { tuple_parameter->users()[i]->set_tuple_index(i); } // Update HloModule shape. hlo_module->mutable_config().SetComputationLayoutIfExists( hlo_module->entry_computation()->ComputeProgramShape()); } VLOG(1) << "Parameter instruction to be reduced: " void ReduceTupleParameter(HloModule* hlo_module) { // Collect all the parameters instructions of tuple type. std::vector<HloInstruction*> tuple_parameters; for (HloInstruction* parameter : hlo_module->entry_computation()->parameter_instructions()) { if (parameter->shape().IsTuple()) { tuple_parameters.push_back(parameter); } } // For each parameter, invokes `ReduceTupleParameterHelper` to reduce its size // of dimensions. No instruction is added or removed from `hlo_module` during // this process, only shapes of parameter instructions and tuple indices of // their uses are updated. for (HloInstruction* tuple_parameter : tuple_parameters) { ReduceTupleParameterHelper(hlo_module, tuple_parameter); } } HloInstruction* FindShardingInstruction(HloModule* hlo_module) { for (HloComputation* computation : hlo_module->computations()) { for (HloInstruction* instruction : computation->instructions()) { if (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == "Sharding") { CHECK_EQ(instruction->operand_count(), 1); return instruction; } } } return nullptr; } void RemoveSharding(HloModule* hlo_module) { while (HloInstruction* custom_call_instruction = FindShardingInstruction(hlo_module)) { // Replace its uses with its operand. for (HloInstruction* user_instruction : custom_call_instruction->users()) { CHECK_OK(custom_call_instruction->ReplaceUseWith( user_instruction, custom_call_instruction->mutable_operand(0))); } // Detach the custom-call from computation. custom_call_instruction->DetachFromOperandsAndUsers(); CHECK_OK(custom_call_instruction->parent()->RemoveInstruction( custom_call_instruction)); VLOG(1) << "Removed sharding custom-call: " << custom_call_instruction->ToString(); // Verify if the module is still valid. HloVerifier verifier(/*layout_sensitive=*/false, /*allow_mixed_precision=*/true); TF_CHECK_OK(verifier.Run(hlo_module).status()); } } VLOG(1) << "Removed sharding custom-call: " void IntraComputationSlicing( const HloComputation* computation, absl::flat_hash_set<const HloInstruction*>& sliced_instructions, absl::flat_hash_set<const HloInstruction*>& frontier_instructions, bool forward_slice, FrontierSelector frontier_selector, bool ignore_control_dependency) { std::deque<const HloInstruction*> worklist(sliced_instructions.begin(), sliced_instructions.end()); while (!worklist.empty()) { const HloInstruction* inst = worklist.back(); worklist.pop_back(); // If `inst` is at the frontier, bookkeep it, and continue. if (frontier_selector && !frontier_selector(inst)) { frontier_instructions.insert(inst); continue; } // Initialize data-dependent instructions std::vector<HloInstruction*> instructions_to_propagate = forward_slice ? std::vector<HloInstruction*>(inst->users().begin(), inst->users().end()) : std::vector<HloInstruction*>(inst->operands().begin(), inst->operands().end()); // Append control-dependent instructions if necessary if (!ignore_control_dependency) { if (forward_slice) { instructions_to_propagate.insert(instructions_to_propagate.end(), inst->control_successors().begin(), inst->control_successors().end()); } else { instructions_to_propagate.insert(instructions_to_propagate.end(), inst->control_predecessors().begin(), inst->control_predecessors().end()); } } for (auto next_inst : instructions_to_propagate) { if (!sliced_instructions.contains(next_inst)) { worklist.push_front(next_inst); sliced_instructions.insert(next_inst); } } } } SliceOutput SliceModuleHelper( const HloModule* hlo_module, absl::Span<const HloInstruction*> slice_starting_instructions, FrontierSelector frontier_selector, bool ignore_control_dependency, bool forward_slice, bool nearest_common_ancestor_as_root) { // Initialize `sliced_computation_instructions_map`, which keeps track of all // the sliced instructions. absl::flat_hash_map<const HloComputation*, absl::flat_hash_set<const HloInstruction*>> sliced_computation_instructions_map; for (auto inst : slice_starting_instructions) { sliced_computation_instructions_map[inst->parent()].insert(inst); } // Initialize `frontier_computation_instructions_map`. absl::flat_hash_map<const HloComputation*, absl::flat_hash_set<const HloInstruction*>> frontier_computation_instructions_map; // Build call graph. std::unique_ptr<CallGraph> call_graph = CallGraph::Build(hlo_module); // Traverse computations in the post-order(forward slicing) or // reverse post-order(backward slicing) manner, and conduct intra-computation // slicing in that order. // // Post-order guarantees that when computation `a` is visited, all of its // callee computations have been visited, thus all the necessary propagation // to `a` has been conducted (i.e., the sliced caller instruction in `a` has // been marked, which serve as the starting point in // `IntraComputationSlicing`). // // Similarly, reverse post-order guarantees that when computation `a` is // visited, all of its caller computations have been visited, thus its root // instruction has been marked, which serve as the starting point in // `IntraComputationSlicing`. std::vector<HloComputation*> post_order_computations = hlo_module->MakeComputationPostOrder(); std::vector<HloComputation*> computations_to_traverse = forward_slice ? post_order_computations : std::vector<HloComputation*>(post_order_computations.rbegin(), post_order_computations.rend()); // If `nearest_common_ancestor_as_root` is enabled, we compute the // HloComputations that hold the `nearest_common_ancestor` instruction, which // are the stopping points when iterating through `computations_to_traverse`. absl::flat_hash_set<const HloComputation*> nearest_common_ancestor_computations; if (nearest_common_ancestor_as_root) { std::vector<const HloComputation*> starting_computations; for (const auto& [computation, instructions] : sliced_computation_instructions_map) { starting_computations.push_back(computation); } nearest_common_ancestor_computations = call_graph->NearestCommonAncestorComputations(starting_computations); CHECK(!nearest_common_ancestor_computations.empty()); } for (auto computation : computations_to_traverse) { if (sliced_computation_instructions_map.contains(computation)) { auto slicing_starting_instructions = std::vector<const HloInstruction*>( sliced_computation_instructions_map[computation].begin(), sliced_computation_instructions_map[computation].end()); // Do intra-computation slicing, starting from the instructions that has // been inserted in `sliced_computation_instructions_map[computation]`. IntraComputationSlicing( computation, sliced_computation_instructions_map[computation], frontier_computation_instructions_map[computation], forward_slice, frontier_selector, ignore_control_dependency); // The block below propagate the slicing results from the current visiting // computation to the next ones. if (forward_slice) { // Check if the current computation is one of the // `nearest_common_ancestor_computations`. If yes, we find the // `nearest_common_ancestor` as an instruction, and stop here. if (nearest_common_ancestor_as_root && nearest_common_ancestor_computations.contains(computation)) { // We use one of the nearest common ancestor instructions. const HloInstruction* nearest_common_ancestor_instruction = *(call_graph->NearestCommonAncestorInstructions( slicing_starting_instructions)) .begin(); CHECK_NE(nearest_common_ancestor_instruction, nullptr); return SliceOutput{sliced_computation_instructions_map, frontier_computation_instructions_map, nearest_common_ancestor_instruction}; } // Skip propagating if the ROOT instruction of the current computation // is NOT sliced. It is either because (1) the sliced instructions are // actually dead code or (2) `frontier_selector` finds frontier and stop // propagation. The found frontier could be at the root instruction, and // in this case, we stop propagation. if (!sliced_computation_instructions_map[computation].contains( computation->root_instruction()) || frontier_computation_instructions_map[computation].contains( computation->root_instruction())) { continue; } // Continue propagating to successors of the current computation, by // inserting its caller computation into // `sliced_computation_instructions_map`, and inserting the caller // instructions as the starting points for intra-computation slicing. for (auto caller_inst : call_graph->GetComputationCallers(computation)) { sliced_computation_instructions_map[caller_inst->parent()].insert( caller_inst); } } if (!forward_slice) { // Propagate to the callee computation of the current computation // that the sliced instructions invoke, by inserting its callee // computation into `sliced_computation_instructions_map`, and inserting // the root instruction of the callee computation as the starting points // for later intra-computation slicing. for (const auto& callsite : call_graph->GetNode(computation).callsites()) { if (sliced_computation_instructions_map[computation].contains( callsite.instruction())) { for (auto callee : callsite.called_computations()) { sliced_computation_instructions_map[callee].insert( callee->root_instruction()); } } } } } } return SliceOutput{sliced_computation_instructions_map, frontier_computation_instructions_map}; } SliceOutput SliceModule( const HloModule* hlo_module, absl::Span<const HloInstruction*> slice_starting_instructions, FrontierSelector frontier_selector, bool ignore_control_dependency, bool forward_slice, bool nearest_common_ancestor_as_root) { if (forward_slice) { if (!nearest_common_ancestor_as_root) { // Forward slicing with the original root as the root. return SliceModuleHelper(hlo_module, slice_starting_instructions, frontier_selector, ignore_control_dependency, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/false); } else { // Forward slicing with the nearest common ancestor (NCA) as the root. // // Internally, this feature is implemented by the following two steps: // 1. Conducting a pass of forward slicing and looking for the NCA // instruction. We first compute the "NCA computation", which is the // NCA, of the computations that hold the // `slice_starting_instructions`. This computation is achieved by // invoking "NearestCommonAncestorComputations" in the call graph. // Then, when we reach the "NCA computation", we compute the NCA of // the instructions that calls the computations which are on the path // from the `slice_starting_instructions` to this NCA computation. // 2. The slice from step 1 contains some redundant instructions, // because, when we do forward slicing, we do not know the exact path // to the NCA, and there could some nodes that cannot be reached from // the NCA. Therefore, in this step, we conduct a pass of backward // slicing from the NCA and filter out the redundant instructions, by // taking the intersection between the backward slicing results and // the forward slicing results from step 1. // Sanity check. CHECK(forward_slice) << "Option `nearest_common_ancestor_as_root` can " "only be enabled when " "forward slicing"; CHECK((frontier_selector == nullptr)) << "Option `nearest_common_ancestor_as_root` can not be specified " "with `frontier_selector`"; // Forward slicing to identify nearest common ancestor SliceOutput forward_slice_output = SliceModuleHelper(hlo_module, slice_starting_instructions, /*frontier_selector=*/nullptr, ignore_control_dependency, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/true); std::vector<const HloInstruction*> nearest_common_ancestor( {forward_slice_output.nearest_common_ancestor_root()}); CHECK_EQ(nearest_common_ancestor.size(), 1); // Backward slicing from the nearest common ancestor to filter out // the redundant computations/instructions in the sliced result in step 1. SliceOutput backward_slice_output = SliceModuleHelper(hlo_module, /*slice_starting_instructions=*/ absl::MakeSpan(nearest_common_ancestor), /*frontier_selector=*/nullptr, ignore_control_dependency, /*forward_slice=*/false, /*nearest_common_ancestor_as_root=*/false); // Intersect the sliced instructions between forward slicing pass and // backward slicing pass as the new sliced instructions, and return the // new SliceOutput. return SliceOutput{SliceOutput::IntersectSlicedInstructions( forward_slice_output, backward_slice_output), backward_slice_output.frontier_instructions(), forward_slice_output.nearest_common_ancestor_root()}; } } else { // Backward slicing. return SliceModuleHelper(hlo_module, slice_starting_instructions, frontier_selector, ignore_control_dependency, /*forward_slice=*/false, /*nearest_common_ancestor_as_root=*/false); } } std::vector<std::unique_ptr<HloModule>> SliceModuleAndExtract( const HloModule* hlo_module, absl::Span<const HloInstruction*> slice_starting_instructions, const SlicingConfiguration& slicing_configuration) { std::vector<std::unique_ptr<HloModule>> sliced_modules; // Group `slice_starting_instructions` based on `slicing_group` configuration. int slicing_group = slicing_configuration.slicing_group; CHECK(slicing_group >= 1 || slicing_group == -1); std::vector<absl::Span<const HloInstruction*>> grouped_instructions; if (slicing_group == -1) { grouped_instructions = {slice_starting_instructions}; } else { for (int i = 0; i < slice_starting_instructions.size(); i += slicing_group) { // subspan can correctly handel the last group, which may be smaller than // `slicing_group`. grouped_instructions.push_back( slice_starting_instructions.subspan(i, slicing_group)); } } for (const auto& grouped_slice_starting_instructions : grouped_instructions) { // Forward slicing. SliceOutput forward_slice_output; if (slicing_configuration.forward_slicing == SlicingConfiguration::ForwardSlicingConfig::kRoot) { // Slice to the root instruction of the entry computation of `hlo_module`. forward_slice_output = SliceModule( hlo_module, grouped_slice_starting_instructions, /*frontier_selector=*/nullptr, /*ignore_control_dependency=*/false, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/false); } else if (slicing_configuration.forward_slicing == SlicingConfiguration::ForwardSlicingConfig::kNca) { // slice to the nearest common ancestors of // `grouped_slice_starting_instructions` forward_slice_output = SliceModule( hlo_module, grouped_slice_starting_instructions, /*frontier_selector=*/nullptr, /*ignore_control_dependency=*/false, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/true); } VLOG(1) << "[Num of forward sliced insts]: " << forward_slice_output.NumSlicedInstructions(); // Backward slicing. SliceOutput backward_slice_output; if (slicing_configuration.backward_slicing) { backward_slice_output = SliceModule( hlo_module, grouped_slice_starting_instructions, /*frontier_selector=*/nullptr, /*ignore_control_dependency=*/false, /*forward_slice=*/false); } else { // Return the empty SliceOutput if backward slicing is not enabled. backward_slice_output = SliceOutput(); } // Combine forward slicing output and backward slicing output. auto sliced_result = SliceOutput(SliceOutput::UnionSlicedInstructions( forward_slice_output, backward_slice_output)); // Decide Root to start extraction based on `forward_slicing_config`. const HloInstruction* extraction_root = slicing_configuration.forward_slicing == SlicingConfiguration::ForwardSlicingConfig::kNca ? forward_slice_output.nearest_common_ancestor_root() : hlo_module->entry_computation()->root_instruction(); VLOG(1) << "[Root instruction of the sliced module]: " << extraction_root->ToString(); // Exclude the instructions that are not in the slicing results. auto extract_selector = [&sliced_result](const HloInstruction* hlo_inst) { for (const auto& [computation, instructions] : sliced_result.sliced_instructions()) { if (instructions.contains(hlo_inst)) { return true; } } return false; }; // Replace the excluded instructions in the entry computation with zeros. auto replace_type_selector = [](const HloInstruction* hlo_inst) -> ReplaceType { return ReplaceType::kReplaceZeroBroadcast; }; // Extract from the original module. auto extracted_module = ExtractModule(/*instruction=*/extraction_root, /*height=*/-1, /*extract_selector=*/extract_selector, /*replace_type_selector=*/replace_type_selector, /*cross_computation=*/true); // Remove the custom-call to sharding if `remove_sharding` is specified. if (slicing_configuration.remove_sharding) { RemoveSharding(extracted_module.get()); } // Reduce the parameter instructions of tuple shape if // `reduce_tuple_parameter` is specified. if (slicing_configuration.reduce_tuple_parameter) { ReduceTupleParameter(extracted_module.get()); } // Verify if the extracted module (after processing) is valid or not. HloVerifier verifier(/*layout_sensitive=*/false, /*allow_mixed_precision=*/true); TF_CHECK_OK(verifier.Run(extracted_module.get()).status()); sliced_modules.emplace_back(std::move(extracted_module)); } // Return all the sliced modules. CHECK_EQ(sliced_modules.size(), grouped_instructions.size()); return sliced_modules; } VLOG(1) << "[Num of forward sliced insts]: " VLOG(1) << "[Root instruction of the sliced module]: " auto extract_selector = [&sliced_result](const HloInstruction* hlo_inst) { for (const auto& [computation, instructions] : sliced_result.sliced_instructions()) { if (instructions.contains(hlo_inst)) { return true; } } return false; };
#include "xla/tools/hlo_slicer.h" #include <memory> #include <string> #include <utility> #include <vector> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/log/check.h" #include "absl/types/span.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/tests/hlo_test_base.h" #include "tsl/platform/statusor.h" TEST_F(HloSlicerTest, MultipleComputationForwardSlice) { const std::string& hlo_string = R"( HloModule test calculate_alpha { constant.5 = s32[] constant(2) constant.6 = s32[] constant(3) ROOT ret = s32[] subtract(constant.5, constant.6) } While.body { loop_var.1 = (s32[], s32[3]{0}) parameter(0) get_tuple_element.1 = s32[] get-tuple-element(loop_var.1), index=0 constant.1 = s32[] constant(23) add.3 = s32[] add(get_tuple_element.1, constant.1) get_tuple_element.2 = s32[3]{0} get-tuple-element(loop_var.1), index=1 multiply = s32[3]{0} multiply(get_tuple_element.2, get_tuple_element.2) ROOT tuple = (s32[], s32[3]{0}) tuple(add.3, multiply) } While.condition { loop_var.2 = (s32[], s32[3]{0}) parameter(0) get_tuple_element.3 = s32[] get-tuple-element(loop_var.2), index=0 constant.2 = s32[] constant(100) ROOT less_than = pred[] compare(get_tuple_element.3, constant.2), direction=LT } ENTRY Test { p.1 = s32[] parameter(0) p.2 = s32[] parameter(1) add.1 = s32[] add(p.1, p.2) constant.3 = s32[] call(), to_apply=calculate_alpha constant.4 = s32[3]{0} constant({0, 1, 2}) tuple.1 = (s32[], s32[3]{0}) tuple(constant.3, constant.4) while.1 = (s32[], s32[3]{0}) while(tuple.1), condition=While.condition, body=While.body loop_count = s32[] get-tuple-element(while.1), index=0 ROOT add.2 = s32[] add(loop_count, add.1) } )"; TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> hlo_module, ParseAndReturnVerifiedModule(hlo_string)); auto add1 = FindInstruction(hlo_module.get(), "add.1"); EXPECT_THAT(add1, op::Add()); auto while1 = FindInstruction(hlo_module.get(), "while.1"); EXPECT_THAT(while1, op::While()); auto loop_count = FindInstruction(hlo_module.get(), "loop_count"); EXPECT_THAT(loop_count, op::GetTupleElement()); auto add2 = FindInstruction(hlo_module.get(), "add.2"); EXPECT_THAT(add2, op::Add()); auto gte1 = FindInstruction(hlo_module.get(), "get_tuple_element.1"); EXPECT_THAT(gte1, op::GetTupleElement()); auto gte2 = FindInstruction(hlo_module.get(), "get_tuple_element.2"); EXPECT_THAT(gte2, op::GetTupleElement()); auto constant5 = FindInstruction(hlo_module.get(), "constant.5"); EXPECT_THAT(constant5, op::Constant()); auto tuple1 = FindInstruction(hlo_module.get(), "tuple.1"); EXPECT_THAT(tuple1, op::Tuple()); auto entry_comp = FindComputation(hlo_module.get(), "Test"); EXPECT_NE(entry_comp, nullptr); auto while_cond_comp = FindComputation(hlo_module.get(), "While.condition"); EXPECT_NE(while_cond_comp, nullptr); auto while_body_comp = FindComputation(hlo_module.get(), "While.body"); EXPECT_NE(while_body_comp, nullptr); auto calculate_alpha_comp = FindComputation(hlo_module.get(), "calculate_alpha"); EXPECT_NE(calculate_alpha_comp, nullptr); // Select everything auto hlo_selector = [](const HloInstruction* hlo_inst) -> bool { return true; }; { std::vector<const HloInstruction*> relevant_instructions({add1, while1}); auto sliced_result = SliceModule( hlo_module.get(), absl::MakeSpan(relevant_instructions), hlo_selector); auto sliced_instructions = sliced_result.sliced_instructions(); EXPECT_EQ(sliced_instructions.size(), 1); EXPECT_EQ(sliced_instructions[entry_comp].size(), 4); EXPECT_TRUE(sliced_instructions[entry_comp].contains(add2)); EXPECT_TRUE(sliced_instructions[entry_comp].contains(add1)); EXPECT_TRUE(sliced_instructions[entry_comp].contains(while1)); EXPECT_TRUE(sliced_instructions[entry_comp].contains(loop_count)); EXPECT_EQ(sliced_result.NumFrontierInstructions(), 0); } { std::vector<const HloInstruction*> relevant_instructions({constant5}); auto sliced_result = SliceModule( hlo_module.get(), absl::MakeSpan(relevant_instructions), hlo_selector); auto sliced_instructions = sliced_result.sliced_instructions(); EXPECT_EQ(sliced_instructions.size(), 2); EXPECT_TRUE(sliced_instructions.contains(entry_comp)); EXPECT_TRUE(sliced_instructions.contains(calculate_alpha_comp)); EXPECT_FALSE(sliced_instructions[entry_comp].contains(add1)); EXPECT_EQ(sliced_result.NumFrontierInstructions(), 0); } { std::vector<const HloInstruction*> relevant_instructions({gte2}); auto sliced_result = SliceModule( hlo_module.get(), absl::MakeSpan(relevant_instructions), hlo_selector); auto sliced_instructions = sliced_result.sliced_instructions(); EXPECT_EQ(sliced_instructions.size(), 2); EXPECT_TRUE(sliced_instructions.contains(entry_comp)); EXPECT_TRUE(sliced_instructions.contains(while_body_comp)); EXPECT_FALSE(sliced_instructions.contains(while_cond_comp)); EXPECT_FALSE(sliced_instructions[entry_comp].contains(tuple1)); EXPECT_FALSE(sliced_instructions[entry_comp].contains(add1)); EXPECT_TRUE(sliced_instructions[entry_comp].contains(add2)); EXPECT_FALSE(sliced_instructions[while_body_comp].contains(gte1)); EXPECT_EQ(sliced_result.NumFrontierInstructions(), 0); } }
HloSlicerTest_MultipleComputationForwardSlicingNearestCommonAncestor
xla/tools/hlo_slicer_test.cc
void ReduceTupleParameterHelper(HloModule* hlo_module, HloInstruction* tuple_parameter) { // Only handle the case where all the uses are GetTupleElement. for (HloInstruction* user_inst : tuple_parameter->users()) { if (user_inst->opcode() != HloOpcode::kGetTupleElement) { return; } } VLOG(1) << "Parameter instruction to be reduced: " << tuple_parameter->ToString() << " shape size: " << tuple_parameter->shape().tuple_shapes_size() << " users size: " << tuple_parameter->users().size(); // Collect the shapes of the elements that have users. std::vector<Shape> used_shapes; for (HloInstruction* user_inst : tuple_parameter->users()) { used_shapes.push_back(user_inst->shape()); } // Change the shape of `tuple_parameter` to only include the shape of elements // that have users. Shape new_tuple_shape = ShapeUtil::MakeTupleShape(absl::MakeSpan(used_shapes)); tuple_parameter->mutable_shape()->mutable_tuple_shapes()->clear(); for (const auto& shape : used_shapes) { tuple_parameter->mutable_shape()->mutable_tuple_shapes()->push_back(shape); } // Update the tuple index of all of the users of `tuple_parameter`, so that // they index into the right shape. for (int i = 0; i < tuple_parameter->users().size(); ++i) { tuple_parameter->users()[i]->set_tuple_index(i); } // Update HloModule shape. hlo_module->mutable_config().SetComputationLayoutIfExists( hlo_module->entry_computation()->ComputeProgramShape()); } VLOG(1) << "Parameter instruction to be reduced: " void ReduceTupleParameter(HloModule* hlo_module) { // Collect all the parameters instructions of tuple type. std::vector<HloInstruction*> tuple_parameters; for (HloInstruction* parameter : hlo_module->entry_computation()->parameter_instructions()) { if (parameter->shape().IsTuple()) { tuple_parameters.push_back(parameter); } } // For each parameter, invokes `ReduceTupleParameterHelper` to reduce its size // of dimensions. No instruction is added or removed from `hlo_module` during // this process, only shapes of parameter instructions and tuple indices of // their uses are updated. for (HloInstruction* tuple_parameter : tuple_parameters) { ReduceTupleParameterHelper(hlo_module, tuple_parameter); } } HloInstruction* FindShardingInstruction(HloModule* hlo_module) { for (HloComputation* computation : hlo_module->computations()) { for (HloInstruction* instruction : computation->instructions()) { if (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == "Sharding") { CHECK_EQ(instruction->operand_count(), 1); return instruction; } } } return nullptr; } void RemoveSharding(HloModule* hlo_module) { while (HloInstruction* custom_call_instruction = FindShardingInstruction(hlo_module)) { // Replace its uses with its operand. for (HloInstruction* user_instruction : custom_call_instruction->users()) { CHECK_OK(custom_call_instruction->ReplaceUseWith( user_instruction, custom_call_instruction->mutable_operand(0))); } // Detach the custom-call from computation. custom_call_instruction->DetachFromOperandsAndUsers(); CHECK_OK(custom_call_instruction->parent()->RemoveInstruction( custom_call_instruction)); VLOG(1) << "Removed sharding custom-call: " << custom_call_instruction->ToString(); // Verify if the module is still valid. HloVerifier verifier(/*layout_sensitive=*/false, /*allow_mixed_precision=*/true); TF_CHECK_OK(verifier.Run(hlo_module).status()); } } VLOG(1) << "Removed sharding custom-call: " void IntraComputationSlicing( const HloComputation* computation, absl::flat_hash_set<const HloInstruction*>& sliced_instructions, absl::flat_hash_set<const HloInstruction*>& frontier_instructions, bool forward_slice, FrontierSelector frontier_selector, bool ignore_control_dependency) { std::deque<const HloInstruction*> worklist(sliced_instructions.begin(), sliced_instructions.end()); while (!worklist.empty()) { const HloInstruction* inst = worklist.back(); worklist.pop_back(); // If `inst` is at the frontier, bookkeep it, and continue. if (frontier_selector && !frontier_selector(inst)) { frontier_instructions.insert(inst); continue; } // Initialize data-dependent instructions std::vector<HloInstruction*> instructions_to_propagate = forward_slice ? std::vector<HloInstruction*>(inst->users().begin(), inst->users().end()) : std::vector<HloInstruction*>(inst->operands().begin(), inst->operands().end()); // Append control-dependent instructions if necessary if (!ignore_control_dependency) { if (forward_slice) { instructions_to_propagate.insert(instructions_to_propagate.end(), inst->control_successors().begin(), inst->control_successors().end()); } else { instructions_to_propagate.insert(instructions_to_propagate.end(), inst->control_predecessors().begin(), inst->control_predecessors().end()); } } for (auto next_inst : instructions_to_propagate) { if (!sliced_instructions.contains(next_inst)) { worklist.push_front(next_inst); sliced_instructions.insert(next_inst); } } } } SliceOutput SliceModuleHelper( const HloModule* hlo_module, absl::Span<const HloInstruction*> slice_starting_instructions, FrontierSelector frontier_selector, bool ignore_control_dependency, bool forward_slice, bool nearest_common_ancestor_as_root) { // Initialize `sliced_computation_instructions_map`, which keeps track of all // the sliced instructions. absl::flat_hash_map<const HloComputation*, absl::flat_hash_set<const HloInstruction*>> sliced_computation_instructions_map; for (auto inst : slice_starting_instructions) { sliced_computation_instructions_map[inst->parent()].insert(inst); } // Initialize `frontier_computation_instructions_map`. absl::flat_hash_map<const HloComputation*, absl::flat_hash_set<const HloInstruction*>> frontier_computation_instructions_map; // Build call graph. std::unique_ptr<CallGraph> call_graph = CallGraph::Build(hlo_module); // Traverse computations in the post-order(forward slicing) or // reverse post-order(backward slicing) manner, and conduct intra-computation // slicing in that order. // // Post-order guarantees that when computation `a` is visited, all of its // callee computations have been visited, thus all the necessary propagation // to `a` has been conducted (i.e., the sliced caller instruction in `a` has // been marked, which serve as the starting point in // `IntraComputationSlicing`). // // Similarly, reverse post-order guarantees that when computation `a` is // visited, all of its caller computations have been visited, thus its root // instruction has been marked, which serve as the starting point in // `IntraComputationSlicing`. std::vector<HloComputation*> post_order_computations = hlo_module->MakeComputationPostOrder(); std::vector<HloComputation*> computations_to_traverse = forward_slice ? post_order_computations : std::vector<HloComputation*>(post_order_computations.rbegin(), post_order_computations.rend()); // If `nearest_common_ancestor_as_root` is enabled, we compute the // HloComputations that hold the `nearest_common_ancestor` instruction, which // are the stopping points when iterating through `computations_to_traverse`. absl::flat_hash_set<const HloComputation*> nearest_common_ancestor_computations; if (nearest_common_ancestor_as_root) { std::vector<const HloComputation*> starting_computations; for (const auto& [computation, instructions] : sliced_computation_instructions_map) { starting_computations.push_back(computation); } nearest_common_ancestor_computations = call_graph->NearestCommonAncestorComputations(starting_computations); CHECK(!nearest_common_ancestor_computations.empty()); } for (auto computation : computations_to_traverse) { if (sliced_computation_instructions_map.contains(computation)) { auto slicing_starting_instructions = std::vector<const HloInstruction*>( sliced_computation_instructions_map[computation].begin(), sliced_computation_instructions_map[computation].end()); // Do intra-computation slicing, starting from the instructions that has // been inserted in `sliced_computation_instructions_map[computation]`. IntraComputationSlicing( computation, sliced_computation_instructions_map[computation], frontier_computation_instructions_map[computation], forward_slice, frontier_selector, ignore_control_dependency); // The block below propagate the slicing results from the current visiting // computation to the next ones. if (forward_slice) { // Check if the current computation is one of the // `nearest_common_ancestor_computations`. If yes, we find the // `nearest_common_ancestor` as an instruction, and stop here. if (nearest_common_ancestor_as_root && nearest_common_ancestor_computations.contains(computation)) { // We use one of the nearest common ancestor instructions. const HloInstruction* nearest_common_ancestor_instruction = *(call_graph->NearestCommonAncestorInstructions( slicing_starting_instructions)) .begin(); CHECK_NE(nearest_common_ancestor_instruction, nullptr); return SliceOutput{sliced_computation_instructions_map, frontier_computation_instructions_map, nearest_common_ancestor_instruction}; } // Skip propagating if the ROOT instruction of the current computation // is NOT sliced. It is either because (1) the sliced instructions are // actually dead code or (2) `frontier_selector` finds frontier and stop // propagation. The found frontier could be at the root instruction, and // in this case, we stop propagation. if (!sliced_computation_instructions_map[computation].contains( computation->root_instruction()) || frontier_computation_instructions_map[computation].contains( computation->root_instruction())) { continue; } // Continue propagating to successors of the current computation, by // inserting its caller computation into // `sliced_computation_instructions_map`, and inserting the caller // instructions as the starting points for intra-computation slicing. for (auto caller_inst : call_graph->GetComputationCallers(computation)) { sliced_computation_instructions_map[caller_inst->parent()].insert( caller_inst); } } if (!forward_slice) { // Propagate to the callee computation of the current computation // that the sliced instructions invoke, by inserting its callee // computation into `sliced_computation_instructions_map`, and inserting // the root instruction of the callee computation as the starting points // for later intra-computation slicing. for (const auto& callsite : call_graph->GetNode(computation).callsites()) { if (sliced_computation_instructions_map[computation].contains( callsite.instruction())) { for (auto callee : callsite.called_computations()) { sliced_computation_instructions_map[callee].insert( callee->root_instruction()); } } } } } } return SliceOutput{sliced_computation_instructions_map, frontier_computation_instructions_map}; } SliceOutput SliceModule( const HloModule* hlo_module, absl::Span<const HloInstruction*> slice_starting_instructions, FrontierSelector frontier_selector, bool ignore_control_dependency, bool forward_slice, bool nearest_common_ancestor_as_root) { if (forward_slice) { if (!nearest_common_ancestor_as_root) { // Forward slicing with the original root as the root. return SliceModuleHelper(hlo_module, slice_starting_instructions, frontier_selector, ignore_control_dependency, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/false); } else { // Forward slicing with the nearest common ancestor (NCA) as the root. // // Internally, this feature is implemented by the following two steps: // 1. Conducting a pass of forward slicing and looking for the NCA // instruction. We first compute the "NCA computation", which is the // NCA, of the computations that hold the // `slice_starting_instructions`. This computation is achieved by // invoking "NearestCommonAncestorComputations" in the call graph. // Then, when we reach the "NCA computation", we compute the NCA of // the instructions that calls the computations which are on the path // from the `slice_starting_instructions` to this NCA computation. // 2. The slice from step 1 contains some redundant instructions, // because, when we do forward slicing, we do not know the exact path // to the NCA, and there could some nodes that cannot be reached from // the NCA. Therefore, in this step, we conduct a pass of backward // slicing from the NCA and filter out the redundant instructions, by // taking the intersection between the backward slicing results and // the forward slicing results from step 1. // Sanity check. CHECK(forward_slice) << "Option `nearest_common_ancestor_as_root` can " "only be enabled when " "forward slicing"; CHECK((frontier_selector == nullptr)) << "Option `nearest_common_ancestor_as_root` can not be specified " "with `frontier_selector`"; // Forward slicing to identify nearest common ancestor SliceOutput forward_slice_output = SliceModuleHelper(hlo_module, slice_starting_instructions, /*frontier_selector=*/nullptr, ignore_control_dependency, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/true); std::vector<const HloInstruction*> nearest_common_ancestor( {forward_slice_output.nearest_common_ancestor_root()}); CHECK_EQ(nearest_common_ancestor.size(), 1); // Backward slicing from the nearest common ancestor to filter out // the redundant computations/instructions in the sliced result in step 1. SliceOutput backward_slice_output = SliceModuleHelper(hlo_module, /*slice_starting_instructions=*/ absl::MakeSpan(nearest_common_ancestor), /*frontier_selector=*/nullptr, ignore_control_dependency, /*forward_slice=*/false, /*nearest_common_ancestor_as_root=*/false); // Intersect the sliced instructions between forward slicing pass and // backward slicing pass as the new sliced instructions, and return the // new SliceOutput. return SliceOutput{SliceOutput::IntersectSlicedInstructions( forward_slice_output, backward_slice_output), backward_slice_output.frontier_instructions(), forward_slice_output.nearest_common_ancestor_root()}; } } else { // Backward slicing. return SliceModuleHelper(hlo_module, slice_starting_instructions, frontier_selector, ignore_control_dependency, /*forward_slice=*/false, /*nearest_common_ancestor_as_root=*/false); } } std::vector<std::unique_ptr<HloModule>> SliceModuleAndExtract( const HloModule* hlo_module, absl::Span<const HloInstruction*> slice_starting_instructions, const SlicingConfiguration& slicing_configuration) { std::vector<std::unique_ptr<HloModule>> sliced_modules; // Group `slice_starting_instructions` based on `slicing_group` configuration. int slicing_group = slicing_configuration.slicing_group; CHECK(slicing_group >= 1 || slicing_group == -1); std::vector<absl::Span<const HloInstruction*>> grouped_instructions; if (slicing_group == -1) { grouped_instructions = {slice_starting_instructions}; } else { for (int i = 0; i < slice_starting_instructions.size(); i += slicing_group) { // subspan can correctly handel the last group, which may be smaller than // `slicing_group`. grouped_instructions.push_back( slice_starting_instructions.subspan(i, slicing_group)); } } for (const auto& grouped_slice_starting_instructions : grouped_instructions) { // Forward slicing. SliceOutput forward_slice_output; if (slicing_configuration.forward_slicing == SlicingConfiguration::ForwardSlicingConfig::kRoot) { // Slice to the root instruction of the entry computation of `hlo_module`. forward_slice_output = SliceModule( hlo_module, grouped_slice_starting_instructions, /*frontier_selector=*/nullptr, /*ignore_control_dependency=*/false, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/false); } else if (slicing_configuration.forward_slicing == SlicingConfiguration::ForwardSlicingConfig::kNca) { // slice to the nearest common ancestors of // `grouped_slice_starting_instructions` forward_slice_output = SliceModule( hlo_module, grouped_slice_starting_instructions, /*frontier_selector=*/nullptr, /*ignore_control_dependency=*/false, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/true); } VLOG(1) << "[Num of forward sliced insts]: " << forward_slice_output.NumSlicedInstructions(); // Backward slicing. SliceOutput backward_slice_output; if (slicing_configuration.backward_slicing) { backward_slice_output = SliceModule( hlo_module, grouped_slice_starting_instructions, /*frontier_selector=*/nullptr, /*ignore_control_dependency=*/false, /*forward_slice=*/false); } else { // Return the empty SliceOutput if backward slicing is not enabled. backward_slice_output = SliceOutput(); } // Combine forward slicing output and backward slicing output. auto sliced_result = SliceOutput(SliceOutput::UnionSlicedInstructions( forward_slice_output, backward_slice_output)); // Decide Root to start extraction based on `forward_slicing_config`. const HloInstruction* extraction_root = slicing_configuration.forward_slicing == SlicingConfiguration::ForwardSlicingConfig::kNca ? forward_slice_output.nearest_common_ancestor_root() : hlo_module->entry_computation()->root_instruction(); VLOG(1) << "[Root instruction of the sliced module]: " << extraction_root->ToString(); // Exclude the instructions that are not in the slicing results. auto extract_selector = [&sliced_result](const HloInstruction* hlo_inst) { for (const auto& [computation, instructions] : sliced_result.sliced_instructions()) { if (instructions.contains(hlo_inst)) { return true; } } return false; }; // Replace the excluded instructions in the entry computation with zeros. auto replace_type_selector = [](const HloInstruction* hlo_inst) -> ReplaceType { return ReplaceType::kReplaceZeroBroadcast; }; // Extract from the original module. auto extracted_module = ExtractModule(/*instruction=*/extraction_root, /*height=*/-1, /*extract_selector=*/extract_selector, /*replace_type_selector=*/replace_type_selector, /*cross_computation=*/true); // Remove the custom-call to sharding if `remove_sharding` is specified. if (slicing_configuration.remove_sharding) { RemoveSharding(extracted_module.get()); } // Reduce the parameter instructions of tuple shape if // `reduce_tuple_parameter` is specified. if (slicing_configuration.reduce_tuple_parameter) { ReduceTupleParameter(extracted_module.get()); } // Verify if the extracted module (after processing) is valid or not. HloVerifier verifier(/*layout_sensitive=*/false, /*allow_mixed_precision=*/true); TF_CHECK_OK(verifier.Run(extracted_module.get()).status()); sliced_modules.emplace_back(std::move(extracted_module)); } // Return all the sliced modules. CHECK_EQ(sliced_modules.size(), grouped_instructions.size()); return sliced_modules; } VLOG(1) << "[Num of forward sliced insts]: " VLOG(1) << "[Root instruction of the sliced module]: " auto extract_selector = [&sliced_result](const HloInstruction* hlo_inst) { for (const auto& [computation, instructions] : sliced_result.sliced_instructions()) { if (instructions.contains(hlo_inst)) { return true; } } return false; };
#include "xla/tools/hlo_slicer.h" #include <memory> #include <string> #include <utility> #include <vector> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/log/check.h" #include "absl/types/span.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/tests/hlo_test_base.h" #include "tsl/platform/statusor.h" TEST_F(HloSlicerTest, MultipleComputationForwardSlicingNearestCommonAncestor) { const std::string& hlo_string = R"( HloModule axpy_module calculate_alpha { c.0 = f32[] constant(1) c.1 = f32[] constant(2) ROOT ret.0 = f32[] multiply(c.0, c.1) } calculate_y { c.2 = f32[] constant(2) c.3 = f32[] constant(3) ROOT ret.1 = f32[] add(c.2, c.3) } ENTRY axpy_computation { alpha = f32[] call(), to_apply=calculate_alpha y = f32[] call(), to_apply=calculate_y add.0 = f32[] add(alpha, y) p.0 = f32[] parameter(0) ROOT add.1 = f32[] add(add.0, p.0) } )"; TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> hlo_module, ParseAndReturnVerifiedModule(hlo_string)); auto c0 = FindInstruction(hlo_module.get(), "c.0"); auto ret0 = FindInstruction(hlo_module.get(), "ret.0"); auto c2 = FindInstruction(hlo_module.get(), "c.2"); auto ret1 = FindInstruction(hlo_module.get(), "ret.1"); auto alpha = FindInstruction(hlo_module.get(), "alpha"); auto y = FindInstruction(hlo_module.get(), "y"); auto add0 = FindInstruction(hlo_module.get(), "add.0"); const HloComputation* computation = hlo_module->entry_computation(); const HloComputation* calculate_alpha = FindComputation(hlo_module.get(), "calculate_alpha"); const HloComputation* calculate_y = FindComputation(hlo_module.get(), "calculate_y"); { std::vector<const HloInstruction*> relevant_instructions({c0, c2}); auto sliced_result = SliceModule(hlo_module.get(), absl::MakeSpan(relevant_instructions), /*frontier_selector=*/nullptr, /*ignore_control_dependency=*/false, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/true); EXPECT_NE(sliced_result.nearest_common_ancestor_root(), nullptr); EXPECT_EQ(sliced_result.nearest_common_ancestor_root(), add0); EXPECT_EQ(sliced_result.sliced_instructions().size(), 3); EXPECT_TRUE(sliced_result.sliced_instructions().contains(computation)); EXPECT_TRUE(sliced_result.sliced_instructions().contains(calculate_alpha)); EXPECT_TRUE(sliced_result.sliced_instructions().contains(calculate_y)); auto sliced_instructions = sliced_result.sliced_instructions(); EXPECT_EQ(sliced_result.NumSlicedInstructions(), 7); EXPECT_TRUE(sliced_instructions[calculate_alpha].contains(c0)); EXPECT_TRUE(sliced_instructions[calculate_alpha].contains(ret0)); EXPECT_TRUE(sliced_instructions[calculate_y].contains(c2)); EXPECT_TRUE(sliced_instructions[calculate_y].contains(ret1)); EXPECT_TRUE(sliced_instructions[computation].contains(alpha)); EXPECT_TRUE(sliced_instructions[computation].contains(y)); EXPECT_TRUE(sliced_instructions[computation].contains(add0)); } }
HloSlicerTest_SingleComputationBackwardSliceAndFrontier
xla/tools/hlo_slicer_test.cc
void ReduceTupleParameterHelper(HloModule* hlo_module, HloInstruction* tuple_parameter) { // Only handle the case where all the uses are GetTupleElement. for (HloInstruction* user_inst : tuple_parameter->users()) { if (user_inst->opcode() != HloOpcode::kGetTupleElement) { return; } } VLOG(1) << "Parameter instruction to be reduced: " << tuple_parameter->ToString() << " shape size: " << tuple_parameter->shape().tuple_shapes_size() << " users size: " << tuple_parameter->users().size(); // Collect the shapes of the elements that have users. std::vector<Shape> used_shapes; for (HloInstruction* user_inst : tuple_parameter->users()) { used_shapes.push_back(user_inst->shape()); } // Change the shape of `tuple_parameter` to only include the shape of elements // that have users. Shape new_tuple_shape = ShapeUtil::MakeTupleShape(absl::MakeSpan(used_shapes)); tuple_parameter->mutable_shape()->mutable_tuple_shapes()->clear(); for (const auto& shape : used_shapes) { tuple_parameter->mutable_shape()->mutable_tuple_shapes()->push_back(shape); } // Update the tuple index of all of the users of `tuple_parameter`, so that // they index into the right shape. for (int i = 0; i < tuple_parameter->users().size(); ++i) { tuple_parameter->users()[i]->set_tuple_index(i); } // Update HloModule shape. hlo_module->mutable_config().SetComputationLayoutIfExists( hlo_module->entry_computation()->ComputeProgramShape()); } VLOG(1) << "Parameter instruction to be reduced: " void ReduceTupleParameter(HloModule* hlo_module) { // Collect all the parameters instructions of tuple type. std::vector<HloInstruction*> tuple_parameters; for (HloInstruction* parameter : hlo_module->entry_computation()->parameter_instructions()) { if (parameter->shape().IsTuple()) { tuple_parameters.push_back(parameter); } } // For each parameter, invokes `ReduceTupleParameterHelper` to reduce its size // of dimensions. No instruction is added or removed from `hlo_module` during // this process, only shapes of parameter instructions and tuple indices of // their uses are updated. for (HloInstruction* tuple_parameter : tuple_parameters) { ReduceTupleParameterHelper(hlo_module, tuple_parameter); } } HloInstruction* FindShardingInstruction(HloModule* hlo_module) { for (HloComputation* computation : hlo_module->computations()) { for (HloInstruction* instruction : computation->instructions()) { if (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == "Sharding") { CHECK_EQ(instruction->operand_count(), 1); return instruction; } } } return nullptr; } void RemoveSharding(HloModule* hlo_module) { while (HloInstruction* custom_call_instruction = FindShardingInstruction(hlo_module)) { // Replace its uses with its operand. for (HloInstruction* user_instruction : custom_call_instruction->users()) { CHECK_OK(custom_call_instruction->ReplaceUseWith( user_instruction, custom_call_instruction->mutable_operand(0))); } // Detach the custom-call from computation. custom_call_instruction->DetachFromOperandsAndUsers(); CHECK_OK(custom_call_instruction->parent()->RemoveInstruction( custom_call_instruction)); VLOG(1) << "Removed sharding custom-call: " << custom_call_instruction->ToString(); // Verify if the module is still valid. HloVerifier verifier(/*layout_sensitive=*/false, /*allow_mixed_precision=*/true); TF_CHECK_OK(verifier.Run(hlo_module).status()); } } VLOG(1) << "Removed sharding custom-call: " void IntraComputationSlicing( const HloComputation* computation, absl::flat_hash_set<const HloInstruction*>& sliced_instructions, absl::flat_hash_set<const HloInstruction*>& frontier_instructions, bool forward_slice, FrontierSelector frontier_selector, bool ignore_control_dependency) { std::deque<const HloInstruction*> worklist(sliced_instructions.begin(), sliced_instructions.end()); while (!worklist.empty()) { const HloInstruction* inst = worklist.back(); worklist.pop_back(); // If `inst` is at the frontier, bookkeep it, and continue. if (frontier_selector && !frontier_selector(inst)) { frontier_instructions.insert(inst); continue; } // Initialize data-dependent instructions std::vector<HloInstruction*> instructions_to_propagate = forward_slice ? std::vector<HloInstruction*>(inst->users().begin(), inst->users().end()) : std::vector<HloInstruction*>(inst->operands().begin(), inst->operands().end()); // Append control-dependent instructions if necessary if (!ignore_control_dependency) { if (forward_slice) { instructions_to_propagate.insert(instructions_to_propagate.end(), inst->control_successors().begin(), inst->control_successors().end()); } else { instructions_to_propagate.insert(instructions_to_propagate.end(), inst->control_predecessors().begin(), inst->control_predecessors().end()); } } for (auto next_inst : instructions_to_propagate) { if (!sliced_instructions.contains(next_inst)) { worklist.push_front(next_inst); sliced_instructions.insert(next_inst); } } } } SliceOutput SliceModuleHelper( const HloModule* hlo_module, absl::Span<const HloInstruction*> slice_starting_instructions, FrontierSelector frontier_selector, bool ignore_control_dependency, bool forward_slice, bool nearest_common_ancestor_as_root) { // Initialize `sliced_computation_instructions_map`, which keeps track of all // the sliced instructions. absl::flat_hash_map<const HloComputation*, absl::flat_hash_set<const HloInstruction*>> sliced_computation_instructions_map; for (auto inst : slice_starting_instructions) { sliced_computation_instructions_map[inst->parent()].insert(inst); } // Initialize `frontier_computation_instructions_map`. absl::flat_hash_map<const HloComputation*, absl::flat_hash_set<const HloInstruction*>> frontier_computation_instructions_map; // Build call graph. std::unique_ptr<CallGraph> call_graph = CallGraph::Build(hlo_module); // Traverse computations in the post-order(forward slicing) or // reverse post-order(backward slicing) manner, and conduct intra-computation // slicing in that order. // // Post-order guarantees that when computation `a` is visited, all of its // callee computations have been visited, thus all the necessary propagation // to `a` has been conducted (i.e., the sliced caller instruction in `a` has // been marked, which serve as the starting point in // `IntraComputationSlicing`). // // Similarly, reverse post-order guarantees that when computation `a` is // visited, all of its caller computations have been visited, thus its root // instruction has been marked, which serve as the starting point in // `IntraComputationSlicing`. std::vector<HloComputation*> post_order_computations = hlo_module->MakeComputationPostOrder(); std::vector<HloComputation*> computations_to_traverse = forward_slice ? post_order_computations : std::vector<HloComputation*>(post_order_computations.rbegin(), post_order_computations.rend()); // If `nearest_common_ancestor_as_root` is enabled, we compute the // HloComputations that hold the `nearest_common_ancestor` instruction, which // are the stopping points when iterating through `computations_to_traverse`. absl::flat_hash_set<const HloComputation*> nearest_common_ancestor_computations; if (nearest_common_ancestor_as_root) { std::vector<const HloComputation*> starting_computations; for (const auto& [computation, instructions] : sliced_computation_instructions_map) { starting_computations.push_back(computation); } nearest_common_ancestor_computations = call_graph->NearestCommonAncestorComputations(starting_computations); CHECK(!nearest_common_ancestor_computations.empty()); } for (auto computation : computations_to_traverse) { if (sliced_computation_instructions_map.contains(computation)) { auto slicing_starting_instructions = std::vector<const HloInstruction*>( sliced_computation_instructions_map[computation].begin(), sliced_computation_instructions_map[computation].end()); // Do intra-computation slicing, starting from the instructions that has // been inserted in `sliced_computation_instructions_map[computation]`. IntraComputationSlicing( computation, sliced_computation_instructions_map[computation], frontier_computation_instructions_map[computation], forward_slice, frontier_selector, ignore_control_dependency); // The block below propagate the slicing results from the current visiting // computation to the next ones. if (forward_slice) { // Check if the current computation is one of the // `nearest_common_ancestor_computations`. If yes, we find the // `nearest_common_ancestor` as an instruction, and stop here. if (nearest_common_ancestor_as_root && nearest_common_ancestor_computations.contains(computation)) { // We use one of the nearest common ancestor instructions. const HloInstruction* nearest_common_ancestor_instruction = *(call_graph->NearestCommonAncestorInstructions( slicing_starting_instructions)) .begin(); CHECK_NE(nearest_common_ancestor_instruction, nullptr); return SliceOutput{sliced_computation_instructions_map, frontier_computation_instructions_map, nearest_common_ancestor_instruction}; } // Skip propagating if the ROOT instruction of the current computation // is NOT sliced. It is either because (1) the sliced instructions are // actually dead code or (2) `frontier_selector` finds frontier and stop // propagation. The found frontier could be at the root instruction, and // in this case, we stop propagation. if (!sliced_computation_instructions_map[computation].contains( computation->root_instruction()) || frontier_computation_instructions_map[computation].contains( computation->root_instruction())) { continue; } // Continue propagating to successors of the current computation, by // inserting its caller computation into // `sliced_computation_instructions_map`, and inserting the caller // instructions as the starting points for intra-computation slicing. for (auto caller_inst : call_graph->GetComputationCallers(computation)) { sliced_computation_instructions_map[caller_inst->parent()].insert( caller_inst); } } if (!forward_slice) { // Propagate to the callee computation of the current computation // that the sliced instructions invoke, by inserting its callee // computation into `sliced_computation_instructions_map`, and inserting // the root instruction of the callee computation as the starting points // for later intra-computation slicing. for (const auto& callsite : call_graph->GetNode(computation).callsites()) { if (sliced_computation_instructions_map[computation].contains( callsite.instruction())) { for (auto callee : callsite.called_computations()) { sliced_computation_instructions_map[callee].insert( callee->root_instruction()); } } } } } } return SliceOutput{sliced_computation_instructions_map, frontier_computation_instructions_map}; } SliceOutput SliceModule( const HloModule* hlo_module, absl::Span<const HloInstruction*> slice_starting_instructions, FrontierSelector frontier_selector, bool ignore_control_dependency, bool forward_slice, bool nearest_common_ancestor_as_root) { if (forward_slice) { if (!nearest_common_ancestor_as_root) { // Forward slicing with the original root as the root. return SliceModuleHelper(hlo_module, slice_starting_instructions, frontier_selector, ignore_control_dependency, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/false); } else { // Forward slicing with the nearest common ancestor (NCA) as the root. // // Internally, this feature is implemented by the following two steps: // 1. Conducting a pass of forward slicing and looking for the NCA // instruction. We first compute the "NCA computation", which is the // NCA, of the computations that hold the // `slice_starting_instructions`. This computation is achieved by // invoking "NearestCommonAncestorComputations" in the call graph. // Then, when we reach the "NCA computation", we compute the NCA of // the instructions that calls the computations which are on the path // from the `slice_starting_instructions` to this NCA computation. // 2. The slice from step 1 contains some redundant instructions, // because, when we do forward slicing, we do not know the exact path // to the NCA, and there could some nodes that cannot be reached from // the NCA. Therefore, in this step, we conduct a pass of backward // slicing from the NCA and filter out the redundant instructions, by // taking the intersection between the backward slicing results and // the forward slicing results from step 1. // Sanity check. CHECK(forward_slice) << "Option `nearest_common_ancestor_as_root` can " "only be enabled when " "forward slicing"; CHECK((frontier_selector == nullptr)) << "Option `nearest_common_ancestor_as_root` can not be specified " "with `frontier_selector`"; // Forward slicing to identify nearest common ancestor SliceOutput forward_slice_output = SliceModuleHelper(hlo_module, slice_starting_instructions, /*frontier_selector=*/nullptr, ignore_control_dependency, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/true); std::vector<const HloInstruction*> nearest_common_ancestor( {forward_slice_output.nearest_common_ancestor_root()}); CHECK_EQ(nearest_common_ancestor.size(), 1); // Backward slicing from the nearest common ancestor to filter out // the redundant computations/instructions in the sliced result in step 1. SliceOutput backward_slice_output = SliceModuleHelper(hlo_module, /*slice_starting_instructions=*/ absl::MakeSpan(nearest_common_ancestor), /*frontier_selector=*/nullptr, ignore_control_dependency, /*forward_slice=*/false, /*nearest_common_ancestor_as_root=*/false); // Intersect the sliced instructions between forward slicing pass and // backward slicing pass as the new sliced instructions, and return the // new SliceOutput. return SliceOutput{SliceOutput::IntersectSlicedInstructions( forward_slice_output, backward_slice_output), backward_slice_output.frontier_instructions(), forward_slice_output.nearest_common_ancestor_root()}; } } else { // Backward slicing. return SliceModuleHelper(hlo_module, slice_starting_instructions, frontier_selector, ignore_control_dependency, /*forward_slice=*/false, /*nearest_common_ancestor_as_root=*/false); } } std::vector<std::unique_ptr<HloModule>> SliceModuleAndExtract( const HloModule* hlo_module, absl::Span<const HloInstruction*> slice_starting_instructions, const SlicingConfiguration& slicing_configuration) { std::vector<std::unique_ptr<HloModule>> sliced_modules; // Group `slice_starting_instructions` based on `slicing_group` configuration. int slicing_group = slicing_configuration.slicing_group; CHECK(slicing_group >= 1 || slicing_group == -1); std::vector<absl::Span<const HloInstruction*>> grouped_instructions; if (slicing_group == -1) { grouped_instructions = {slice_starting_instructions}; } else { for (int i = 0; i < slice_starting_instructions.size(); i += slicing_group) { // subspan can correctly handel the last group, which may be smaller than // `slicing_group`. grouped_instructions.push_back( slice_starting_instructions.subspan(i, slicing_group)); } } for (const auto& grouped_slice_starting_instructions : grouped_instructions) { // Forward slicing. SliceOutput forward_slice_output; if (slicing_configuration.forward_slicing == SlicingConfiguration::ForwardSlicingConfig::kRoot) { // Slice to the root instruction of the entry computation of `hlo_module`. forward_slice_output = SliceModule( hlo_module, grouped_slice_starting_instructions, /*frontier_selector=*/nullptr, /*ignore_control_dependency=*/false, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/false); } else if (slicing_configuration.forward_slicing == SlicingConfiguration::ForwardSlicingConfig::kNca) { // slice to the nearest common ancestors of // `grouped_slice_starting_instructions` forward_slice_output = SliceModule( hlo_module, grouped_slice_starting_instructions, /*frontier_selector=*/nullptr, /*ignore_control_dependency=*/false, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/true); } VLOG(1) << "[Num of forward sliced insts]: " << forward_slice_output.NumSlicedInstructions(); // Backward slicing. SliceOutput backward_slice_output; if (slicing_configuration.backward_slicing) { backward_slice_output = SliceModule( hlo_module, grouped_slice_starting_instructions, /*frontier_selector=*/nullptr, /*ignore_control_dependency=*/false, /*forward_slice=*/false); } else { // Return the empty SliceOutput if backward slicing is not enabled. backward_slice_output = SliceOutput(); } // Combine forward slicing output and backward slicing output. auto sliced_result = SliceOutput(SliceOutput::UnionSlicedInstructions( forward_slice_output, backward_slice_output)); // Decide Root to start extraction based on `forward_slicing_config`. const HloInstruction* extraction_root = slicing_configuration.forward_slicing == SlicingConfiguration::ForwardSlicingConfig::kNca ? forward_slice_output.nearest_common_ancestor_root() : hlo_module->entry_computation()->root_instruction(); VLOG(1) << "[Root instruction of the sliced module]: " << extraction_root->ToString(); // Exclude the instructions that are not in the slicing results. auto extract_selector = [&sliced_result](const HloInstruction* hlo_inst) { for (const auto& [computation, instructions] : sliced_result.sliced_instructions()) { if (instructions.contains(hlo_inst)) { return true; } } return false; }; // Replace the excluded instructions in the entry computation with zeros. auto replace_type_selector = [](const HloInstruction* hlo_inst) -> ReplaceType { return ReplaceType::kReplaceZeroBroadcast; }; // Extract from the original module. auto extracted_module = ExtractModule(/*instruction=*/extraction_root, /*height=*/-1, /*extract_selector=*/extract_selector, /*replace_type_selector=*/replace_type_selector, /*cross_computation=*/true); // Remove the custom-call to sharding if `remove_sharding` is specified. if (slicing_configuration.remove_sharding) { RemoveSharding(extracted_module.get()); } // Reduce the parameter instructions of tuple shape if // `reduce_tuple_parameter` is specified. if (slicing_configuration.reduce_tuple_parameter) { ReduceTupleParameter(extracted_module.get()); } // Verify if the extracted module (after processing) is valid or not. HloVerifier verifier(/*layout_sensitive=*/false, /*allow_mixed_precision=*/true); TF_CHECK_OK(verifier.Run(extracted_module.get()).status()); sliced_modules.emplace_back(std::move(extracted_module)); } // Return all the sliced modules. CHECK_EQ(sliced_modules.size(), grouped_instructions.size()); return sliced_modules; } VLOG(1) << "[Num of forward sliced insts]: " VLOG(1) << "[Root instruction of the sliced module]: " auto extract_selector = [&sliced_result](const HloInstruction* hlo_inst) { for (const auto& [computation, instructions] : sliced_result.sliced_instructions()) { if (instructions.contains(hlo_inst)) { return true; } } return false; };
#include "xla/tools/hlo_slicer.h" #include <memory> #include <string> #include <utility> #include <vector> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/log/check.h" #include "absl/types/span.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/tests/hlo_test_base.h" #include "tsl/platform/statusor.h" TEST_F(HloSlicerTest, SingleComputationBackwardSliceAndFrontier) { const std::string& hlo_string = R"( HloModule axpy_module ENTRY axpy_computation { p.0 = f32[10] parameter(0) p.1 = f32[10] parameter(1) add.0 = f32[10] add(p.0, p.1) alpha = f32[] constant(1) broadcast = f32[10] broadcast(alpha), dimensions={} p.2 = f32[10] parameter(2) y = f32[10] multiply(broadcast, p.2) x = f32[10] subtract(y, add.0) p.3 = f32[10] parameter(3) ROOT add.1 = f32[10] add(x, p.3) } )"; TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> hlo_module, ParseAndReturnVerifiedModule(hlo_string)); auto alpha = FindInstruction(hlo_module.get(), "alpha"); EXPECT_THAT(alpha, op::Constant()); auto p0 = FindInstruction(hlo_module.get(), "p.0"); EXPECT_THAT(p0, op::Parameter()); auto p1 = FindInstruction(hlo_module.get(), "p.1"); EXPECT_THAT(p1, op::Parameter()); auto p2 = FindInstruction(hlo_module.get(), "p.2"); EXPECT_THAT(p2, op::Parameter()); auto p3 = FindInstruction(hlo_module.get(), "p.3"); EXPECT_THAT(p3, op::Parameter()); auto broadcast = FindInstruction(hlo_module.get(), "broadcast"); EXPECT_THAT(broadcast, op::Broadcast()); auto x = FindInstruction(hlo_module.get(), "x"); EXPECT_THAT(x, op::Subtract()); auto y = FindInstruction(hlo_module.get(), "y"); EXPECT_THAT(y, op::Multiply()); auto add0 = FindInstruction(hlo_module.get(), "add.0"); EXPECT_THAT(add0, op::Add()); auto entry_comp = FindComputation(hlo_module.get(), "axpy_computation"); EXPECT_NE(entry_comp, nullptr); // Select everything auto hlo_selector = [](const HloInstruction* hlo_inst) -> bool { return true; }; { std::vector<const HloInstruction*> relevant_instructions({y}); auto sliced_result = SliceModule( hlo_module.get(), absl::MakeSpan(relevant_instructions), hlo_selector, /*ignore_control_dependency=*/false, /*forward_slice=*/false); auto sliced_instructions = sliced_result.sliced_instructions(); EXPECT_EQ(sliced_instructions.size(), 1); EXPECT_EQ(sliced_instructions[entry_comp].size(), 4); EXPECT_TRUE(sliced_instructions[entry_comp].contains(y)); EXPECT_TRUE(sliced_instructions[entry_comp].contains(broadcast)); EXPECT_TRUE(sliced_instructions[entry_comp].contains(p2)); EXPECT_TRUE(sliced_instructions[entry_comp].contains(alpha)); EXPECT_EQ(sliced_result.NumFrontierInstructions(), 0); } { std::vector<const HloInstruction*> relevant_instructions({add0, y}); auto sliced_result = SliceModule( hlo_module.get(), absl::MakeSpan(relevant_instructions), hlo_selector, /*ignore_control_dependency=*/false, /*forward_slice=*/false); auto sliced_instructions = sliced_result.sliced_instructions(); EXPECT_EQ(sliced_instructions.size(), 1); EXPECT_EQ(sliced_instructions[entry_comp].size(), 7); EXPECT_TRUE(sliced_instructions[entry_comp].contains(y)); EXPECT_TRUE(sliced_instructions[entry_comp].contains(broadcast)); EXPECT_TRUE(sliced_instructions[entry_comp].contains(p2)); EXPECT_TRUE(sliced_instructions[entry_comp].contains(alpha)); EXPECT_TRUE(sliced_instructions[entry_comp].contains(add0)); EXPECT_TRUE(sliced_instructions[entry_comp].contains(p0)); EXPECT_TRUE(sliced_instructions[entry_comp].contains(p1)); EXPECT_EQ(sliced_result.NumFrontierInstructions(), 0); } // Testing backward frontier // Slice at Broadcast. auto broadcast_slicer = [](const HloInstruction* hlo_inst) -> bool { return hlo_inst->opcode() != HloOpcode::kBroadcast; }; { std::vector<const HloInstruction*> relevant_instructions({y}); auto sliced_result = SliceModule( hlo_module.get(), absl::MakeSpan(relevant_instructions), broadcast_slicer, /*ignore_control_dependency=*/false, /*forward_slice=*/false); auto sliced_instructions = sliced_result.sliced_instructions(); EXPECT_EQ(sliced_instructions.size(), 1); EXPECT_EQ(sliced_instructions[entry_comp].size(), 3); EXPECT_TRUE(sliced_instructions[entry_comp].contains(y)); EXPECT_TRUE(sliced_instructions[entry_comp].contains(p2)); EXPECT_TRUE(sliced_instructions[entry_comp].contains(broadcast)); EXPECT_EQ(sliced_result.NumFrontierInstructions(), 1); auto frontier_instructions = sliced_result.frontier_instructions(); EXPECT_TRUE(frontier_instructions[entry_comp].contains(broadcast)); } }
HloSlicerTest_SingleComputationForwardFrontier
xla/tools/hlo_slicer_test.cc
void ReduceTupleParameterHelper(HloModule* hlo_module, HloInstruction* tuple_parameter) { // Only handle the case where all the uses are GetTupleElement. for (HloInstruction* user_inst : tuple_parameter->users()) { if (user_inst->opcode() != HloOpcode::kGetTupleElement) { return; } } VLOG(1) << "Parameter instruction to be reduced: " << tuple_parameter->ToString() << " shape size: " << tuple_parameter->shape().tuple_shapes_size() << " users size: " << tuple_parameter->users().size(); // Collect the shapes of the elements that have users. std::vector<Shape> used_shapes; for (HloInstruction* user_inst : tuple_parameter->users()) { used_shapes.push_back(user_inst->shape()); } // Change the shape of `tuple_parameter` to only include the shape of elements // that have users. Shape new_tuple_shape = ShapeUtil::MakeTupleShape(absl::MakeSpan(used_shapes)); tuple_parameter->mutable_shape()->mutable_tuple_shapes()->clear(); for (const auto& shape : used_shapes) { tuple_parameter->mutable_shape()->mutable_tuple_shapes()->push_back(shape); } // Update the tuple index of all of the users of `tuple_parameter`, so that // they index into the right shape. for (int i = 0; i < tuple_parameter->users().size(); ++i) { tuple_parameter->users()[i]->set_tuple_index(i); } // Update HloModule shape. hlo_module->mutable_config().SetComputationLayoutIfExists( hlo_module->entry_computation()->ComputeProgramShape()); } VLOG(1) << "Parameter instruction to be reduced: " void ReduceTupleParameter(HloModule* hlo_module) { // Collect all the parameters instructions of tuple type. std::vector<HloInstruction*> tuple_parameters; for (HloInstruction* parameter : hlo_module->entry_computation()->parameter_instructions()) { if (parameter->shape().IsTuple()) { tuple_parameters.push_back(parameter); } } // For each parameter, invokes `ReduceTupleParameterHelper` to reduce its size // of dimensions. No instruction is added or removed from `hlo_module` during // this process, only shapes of parameter instructions and tuple indices of // their uses are updated. for (HloInstruction* tuple_parameter : tuple_parameters) { ReduceTupleParameterHelper(hlo_module, tuple_parameter); } } HloInstruction* FindShardingInstruction(HloModule* hlo_module) { for (HloComputation* computation : hlo_module->computations()) { for (HloInstruction* instruction : computation->instructions()) { if (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == "Sharding") { CHECK_EQ(instruction->operand_count(), 1); return instruction; } } } return nullptr; } void RemoveSharding(HloModule* hlo_module) { while (HloInstruction* custom_call_instruction = FindShardingInstruction(hlo_module)) { // Replace its uses with its operand. for (HloInstruction* user_instruction : custom_call_instruction->users()) { CHECK_OK(custom_call_instruction->ReplaceUseWith( user_instruction, custom_call_instruction->mutable_operand(0))); } // Detach the custom-call from computation. custom_call_instruction->DetachFromOperandsAndUsers(); CHECK_OK(custom_call_instruction->parent()->RemoveInstruction( custom_call_instruction)); VLOG(1) << "Removed sharding custom-call: " << custom_call_instruction->ToString(); // Verify if the module is still valid. HloVerifier verifier(/*layout_sensitive=*/false, /*allow_mixed_precision=*/true); TF_CHECK_OK(verifier.Run(hlo_module).status()); } } VLOG(1) << "Removed sharding custom-call: " void IntraComputationSlicing( const HloComputation* computation, absl::flat_hash_set<const HloInstruction*>& sliced_instructions, absl::flat_hash_set<const HloInstruction*>& frontier_instructions, bool forward_slice, FrontierSelector frontier_selector, bool ignore_control_dependency) { std::deque<const HloInstruction*> worklist(sliced_instructions.begin(), sliced_instructions.end()); while (!worklist.empty()) { const HloInstruction* inst = worklist.back(); worklist.pop_back(); // If `inst` is at the frontier, bookkeep it, and continue. if (frontier_selector && !frontier_selector(inst)) { frontier_instructions.insert(inst); continue; } // Initialize data-dependent instructions std::vector<HloInstruction*> instructions_to_propagate = forward_slice ? std::vector<HloInstruction*>(inst->users().begin(), inst->users().end()) : std::vector<HloInstruction*>(inst->operands().begin(), inst->operands().end()); // Append control-dependent instructions if necessary if (!ignore_control_dependency) { if (forward_slice) { instructions_to_propagate.insert(instructions_to_propagate.end(), inst->control_successors().begin(), inst->control_successors().end()); } else { instructions_to_propagate.insert(instructions_to_propagate.end(), inst->control_predecessors().begin(), inst->control_predecessors().end()); } } for (auto next_inst : instructions_to_propagate) { if (!sliced_instructions.contains(next_inst)) { worklist.push_front(next_inst); sliced_instructions.insert(next_inst); } } } } SliceOutput SliceModuleHelper( const HloModule* hlo_module, absl::Span<const HloInstruction*> slice_starting_instructions, FrontierSelector frontier_selector, bool ignore_control_dependency, bool forward_slice, bool nearest_common_ancestor_as_root) { // Initialize `sliced_computation_instructions_map`, which keeps track of all // the sliced instructions. absl::flat_hash_map<const HloComputation*, absl::flat_hash_set<const HloInstruction*>> sliced_computation_instructions_map; for (auto inst : slice_starting_instructions) { sliced_computation_instructions_map[inst->parent()].insert(inst); } // Initialize `frontier_computation_instructions_map`. absl::flat_hash_map<const HloComputation*, absl::flat_hash_set<const HloInstruction*>> frontier_computation_instructions_map; // Build call graph. std::unique_ptr<CallGraph> call_graph = CallGraph::Build(hlo_module); // Traverse computations in the post-order(forward slicing) or // reverse post-order(backward slicing) manner, and conduct intra-computation // slicing in that order. // // Post-order guarantees that when computation `a` is visited, all of its // callee computations have been visited, thus all the necessary propagation // to `a` has been conducted (i.e., the sliced caller instruction in `a` has // been marked, which serve as the starting point in // `IntraComputationSlicing`). // // Similarly, reverse post-order guarantees that when computation `a` is // visited, all of its caller computations have been visited, thus its root // instruction has been marked, which serve as the starting point in // `IntraComputationSlicing`. std::vector<HloComputation*> post_order_computations = hlo_module->MakeComputationPostOrder(); std::vector<HloComputation*> computations_to_traverse = forward_slice ? post_order_computations : std::vector<HloComputation*>(post_order_computations.rbegin(), post_order_computations.rend()); // If `nearest_common_ancestor_as_root` is enabled, we compute the // HloComputations that hold the `nearest_common_ancestor` instruction, which // are the stopping points when iterating through `computations_to_traverse`. absl::flat_hash_set<const HloComputation*> nearest_common_ancestor_computations; if (nearest_common_ancestor_as_root) { std::vector<const HloComputation*> starting_computations; for (const auto& [computation, instructions] : sliced_computation_instructions_map) { starting_computations.push_back(computation); } nearest_common_ancestor_computations = call_graph->NearestCommonAncestorComputations(starting_computations); CHECK(!nearest_common_ancestor_computations.empty()); } for (auto computation : computations_to_traverse) { if (sliced_computation_instructions_map.contains(computation)) { auto slicing_starting_instructions = std::vector<const HloInstruction*>( sliced_computation_instructions_map[computation].begin(), sliced_computation_instructions_map[computation].end()); // Do intra-computation slicing, starting from the instructions that has // been inserted in `sliced_computation_instructions_map[computation]`. IntraComputationSlicing( computation, sliced_computation_instructions_map[computation], frontier_computation_instructions_map[computation], forward_slice, frontier_selector, ignore_control_dependency); // The block below propagate the slicing results from the current visiting // computation to the next ones. if (forward_slice) { // Check if the current computation is one of the // `nearest_common_ancestor_computations`. If yes, we find the // `nearest_common_ancestor` as an instruction, and stop here. if (nearest_common_ancestor_as_root && nearest_common_ancestor_computations.contains(computation)) { // We use one of the nearest common ancestor instructions. const HloInstruction* nearest_common_ancestor_instruction = *(call_graph->NearestCommonAncestorInstructions( slicing_starting_instructions)) .begin(); CHECK_NE(nearest_common_ancestor_instruction, nullptr); return SliceOutput{sliced_computation_instructions_map, frontier_computation_instructions_map, nearest_common_ancestor_instruction}; } // Skip propagating if the ROOT instruction of the current computation // is NOT sliced. It is either because (1) the sliced instructions are // actually dead code or (2) `frontier_selector` finds frontier and stop // propagation. The found frontier could be at the root instruction, and // in this case, we stop propagation. if (!sliced_computation_instructions_map[computation].contains( computation->root_instruction()) || frontier_computation_instructions_map[computation].contains( computation->root_instruction())) { continue; } // Continue propagating to successors of the current computation, by // inserting its caller computation into // `sliced_computation_instructions_map`, and inserting the caller // instructions as the starting points for intra-computation slicing. for (auto caller_inst : call_graph->GetComputationCallers(computation)) { sliced_computation_instructions_map[caller_inst->parent()].insert( caller_inst); } } if (!forward_slice) { // Propagate to the callee computation of the current computation // that the sliced instructions invoke, by inserting its callee // computation into `sliced_computation_instructions_map`, and inserting // the root instruction of the callee computation as the starting points // for later intra-computation slicing. for (const auto& callsite : call_graph->GetNode(computation).callsites()) { if (sliced_computation_instructions_map[computation].contains( callsite.instruction())) { for (auto callee : callsite.called_computations()) { sliced_computation_instructions_map[callee].insert( callee->root_instruction()); } } } } } } return SliceOutput{sliced_computation_instructions_map, frontier_computation_instructions_map}; } SliceOutput SliceModule( const HloModule* hlo_module, absl::Span<const HloInstruction*> slice_starting_instructions, FrontierSelector frontier_selector, bool ignore_control_dependency, bool forward_slice, bool nearest_common_ancestor_as_root) { if (forward_slice) { if (!nearest_common_ancestor_as_root) { // Forward slicing with the original root as the root. return SliceModuleHelper(hlo_module, slice_starting_instructions, frontier_selector, ignore_control_dependency, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/false); } else { // Forward slicing with the nearest common ancestor (NCA) as the root. // // Internally, this feature is implemented by the following two steps: // 1. Conducting a pass of forward slicing and looking for the NCA // instruction. We first compute the "NCA computation", which is the // NCA, of the computations that hold the // `slice_starting_instructions`. This computation is achieved by // invoking "NearestCommonAncestorComputations" in the call graph. // Then, when we reach the "NCA computation", we compute the NCA of // the instructions that calls the computations which are on the path // from the `slice_starting_instructions` to this NCA computation. // 2. The slice from step 1 contains some redundant instructions, // because, when we do forward slicing, we do not know the exact path // to the NCA, and there could some nodes that cannot be reached from // the NCA. Therefore, in this step, we conduct a pass of backward // slicing from the NCA and filter out the redundant instructions, by // taking the intersection between the backward slicing results and // the forward slicing results from step 1. // Sanity check. CHECK(forward_slice) << "Option `nearest_common_ancestor_as_root` can " "only be enabled when " "forward slicing"; CHECK((frontier_selector == nullptr)) << "Option `nearest_common_ancestor_as_root` can not be specified " "with `frontier_selector`"; // Forward slicing to identify nearest common ancestor SliceOutput forward_slice_output = SliceModuleHelper(hlo_module, slice_starting_instructions, /*frontier_selector=*/nullptr, ignore_control_dependency, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/true); std::vector<const HloInstruction*> nearest_common_ancestor( {forward_slice_output.nearest_common_ancestor_root()}); CHECK_EQ(nearest_common_ancestor.size(), 1); // Backward slicing from the nearest common ancestor to filter out // the redundant computations/instructions in the sliced result in step 1. SliceOutput backward_slice_output = SliceModuleHelper(hlo_module, /*slice_starting_instructions=*/ absl::MakeSpan(nearest_common_ancestor), /*frontier_selector=*/nullptr, ignore_control_dependency, /*forward_slice=*/false, /*nearest_common_ancestor_as_root=*/false); // Intersect the sliced instructions between forward slicing pass and // backward slicing pass as the new sliced instructions, and return the // new SliceOutput. return SliceOutput{SliceOutput::IntersectSlicedInstructions( forward_slice_output, backward_slice_output), backward_slice_output.frontier_instructions(), forward_slice_output.nearest_common_ancestor_root()}; } } else { // Backward slicing. return SliceModuleHelper(hlo_module, slice_starting_instructions, frontier_selector, ignore_control_dependency, /*forward_slice=*/false, /*nearest_common_ancestor_as_root=*/false); } } std::vector<std::unique_ptr<HloModule>> SliceModuleAndExtract( const HloModule* hlo_module, absl::Span<const HloInstruction*> slice_starting_instructions, const SlicingConfiguration& slicing_configuration) { std::vector<std::unique_ptr<HloModule>> sliced_modules; // Group `slice_starting_instructions` based on `slicing_group` configuration. int slicing_group = slicing_configuration.slicing_group; CHECK(slicing_group >= 1 || slicing_group == -1); std::vector<absl::Span<const HloInstruction*>> grouped_instructions; if (slicing_group == -1) { grouped_instructions = {slice_starting_instructions}; } else { for (int i = 0; i < slice_starting_instructions.size(); i += slicing_group) { // subspan can correctly handel the last group, which may be smaller than // `slicing_group`. grouped_instructions.push_back( slice_starting_instructions.subspan(i, slicing_group)); } } for (const auto& grouped_slice_starting_instructions : grouped_instructions) { // Forward slicing. SliceOutput forward_slice_output; if (slicing_configuration.forward_slicing == SlicingConfiguration::ForwardSlicingConfig::kRoot) { // Slice to the root instruction of the entry computation of `hlo_module`. forward_slice_output = SliceModule( hlo_module, grouped_slice_starting_instructions, /*frontier_selector=*/nullptr, /*ignore_control_dependency=*/false, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/false); } else if (slicing_configuration.forward_slicing == SlicingConfiguration::ForwardSlicingConfig::kNca) { // slice to the nearest common ancestors of // `grouped_slice_starting_instructions` forward_slice_output = SliceModule( hlo_module, grouped_slice_starting_instructions, /*frontier_selector=*/nullptr, /*ignore_control_dependency=*/false, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/true); } VLOG(1) << "[Num of forward sliced insts]: " << forward_slice_output.NumSlicedInstructions(); // Backward slicing. SliceOutput backward_slice_output; if (slicing_configuration.backward_slicing) { backward_slice_output = SliceModule( hlo_module, grouped_slice_starting_instructions, /*frontier_selector=*/nullptr, /*ignore_control_dependency=*/false, /*forward_slice=*/false); } else { // Return the empty SliceOutput if backward slicing is not enabled. backward_slice_output = SliceOutput(); } // Combine forward slicing output and backward slicing output. auto sliced_result = SliceOutput(SliceOutput::UnionSlicedInstructions( forward_slice_output, backward_slice_output)); // Decide Root to start extraction based on `forward_slicing_config`. const HloInstruction* extraction_root = slicing_configuration.forward_slicing == SlicingConfiguration::ForwardSlicingConfig::kNca ? forward_slice_output.nearest_common_ancestor_root() : hlo_module->entry_computation()->root_instruction(); VLOG(1) << "[Root instruction of the sliced module]: " << extraction_root->ToString(); // Exclude the instructions that are not in the slicing results. auto extract_selector = [&sliced_result](const HloInstruction* hlo_inst) { for (const auto& [computation, instructions] : sliced_result.sliced_instructions()) { if (instructions.contains(hlo_inst)) { return true; } } return false; }; // Replace the excluded instructions in the entry computation with zeros. auto replace_type_selector = [](const HloInstruction* hlo_inst) -> ReplaceType { return ReplaceType::kReplaceZeroBroadcast; }; // Extract from the original module. auto extracted_module = ExtractModule(/*instruction=*/extraction_root, /*height=*/-1, /*extract_selector=*/extract_selector, /*replace_type_selector=*/replace_type_selector, /*cross_computation=*/true); // Remove the custom-call to sharding if `remove_sharding` is specified. if (slicing_configuration.remove_sharding) { RemoveSharding(extracted_module.get()); } // Reduce the parameter instructions of tuple shape if // `reduce_tuple_parameter` is specified. if (slicing_configuration.reduce_tuple_parameter) { ReduceTupleParameter(extracted_module.get()); } // Verify if the extracted module (after processing) is valid or not. HloVerifier verifier(/*layout_sensitive=*/false, /*allow_mixed_precision=*/true); TF_CHECK_OK(verifier.Run(extracted_module.get()).status()); sliced_modules.emplace_back(std::move(extracted_module)); } // Return all the sliced modules. CHECK_EQ(sliced_modules.size(), grouped_instructions.size()); return sliced_modules; } VLOG(1) << "[Num of forward sliced insts]: " VLOG(1) << "[Root instruction of the sliced module]: " auto extract_selector = [&sliced_result](const HloInstruction* hlo_inst) { for (const auto& [computation, instructions] : sliced_result.sliced_instructions()) { if (instructions.contains(hlo_inst)) { return true; } } return false; };
#include "xla/tools/hlo_slicer.h" #include <memory> #include <string> #include <utility> #include <vector> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/log/check.h" #include "absl/types/span.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/tests/hlo_test_base.h" #include "tsl/platform/statusor.h" TEST_F(HloSlicerTest, SingleComputationForwardFrontier) { const std::string& hlo_string = R"( HloModule axpy_module ENTRY axpy_computation { p.0 = f32[10] parameter(0) p.1 = f32[10] parameter(1) add.0 = f32[10] add(p.0, p.1) alpha = f32[] constant(1) broadcast = f32[10] broadcast(alpha), dimensions={} p.2 = f32[10] parameter(2) y = f32[10] multiply(broadcast, p.2) x = f32[10] subtract(y, add.0) p.3 = f32[10] parameter(3) p.4 = f32[10] parameter(4) p.5 = f32[10] parameter(5) sub.1 = f32[10] subtract(p.4, p.5) add.2 = f32[10] add(p.3, sub.1) ROOT add.1 = f32[10] add(x, add.2) } )"; TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> hlo_module, ParseAndReturnVerifiedModule(hlo_string)); auto broadcast = FindInstruction(hlo_module.get(), "broadcast"); EXPECT_THAT(broadcast, op::Broadcast()); auto x = FindInstruction(hlo_module.get(), "x"); EXPECT_THAT(x, op::Subtract()); auto y = FindInstruction(hlo_module.get(), "y"); EXPECT_THAT(y, op::Multiply()); auto add0 = FindInstruction(hlo_module.get(), "add.0"); EXPECT_THAT(add0, op::Add()); auto p5 = FindInstruction(hlo_module.get(), "p.5"); EXPECT_THAT(p5, op::Parameter()); auto sub1 = FindInstruction(hlo_module.get(), "sub.1"); EXPECT_THAT(sub1, op::Subtract()); auto entry_comp = FindComputation(hlo_module.get(), "axpy_computation"); EXPECT_NE(entry_comp, nullptr); { // Slice at Subtract auto hlo_selector = [](const HloInstruction* hlo_inst) -> bool { return hlo_inst->opcode() != HloOpcode::kSubtract; }; std::vector<const HloInstruction*> relevant_instructions({broadcast, add0}); auto sliced_result = SliceModule( hlo_module.get(), absl::MakeSpan(relevant_instructions), hlo_selector); auto sliced_instructions = sliced_result.sliced_instructions(); EXPECT_EQ(sliced_result.NumSlicedInstructions(), 4); EXPECT_EQ(sliced_instructions.size(), 1); EXPECT_TRUE(sliced_instructions[entry_comp].contains(add0)); EXPECT_TRUE(sliced_instructions[entry_comp].contains(broadcast)); EXPECT_TRUE(sliced_instructions[entry_comp].contains(y)); EXPECT_TRUE(sliced_instructions[entry_comp].contains(x)); EXPECT_EQ(sliced_result.NumFrontierInstructions(), 1); auto frontier_instructions = sliced_result.frontier_instructions(); EXPECT_TRUE(frontier_instructions[entry_comp].contains(x)); } { // Slice at Subtract auto hlo_selector = [](const HloInstruction* hlo_inst) -> bool { return hlo_inst->opcode() != HloOpcode::kSubtract; }; std::vector<const HloInstruction*> relevant_instructions({add0, y, p5}); auto sliced_result = SliceModule( hlo_module.get(), absl::MakeSpan(relevant_instructions), hlo_selector); auto sliced_instructions = sliced_result.sliced_instructions(); EXPECT_EQ(sliced_result.NumSlicedInstructions(), 5); EXPECT_EQ(sliced_instructions.size(), 1); EXPECT_TRUE(sliced_instructions[entry_comp].contains(add0)); EXPECT_TRUE(sliced_instructions[entry_comp].contains(y)); EXPECT_TRUE(sliced_instructions[entry_comp].contains(x)); EXPECT_TRUE(sliced_instructions[entry_comp].contains(p5)); EXPECT_TRUE(sliced_instructions[entry_comp].contains(sub1)); EXPECT_EQ(sliced_result.NumFrontierInstructions(), 2); auto frontier_instructions = sliced_result.frontier_instructions(); EXPECT_TRUE(frontier_instructions[entry_comp].contains(x)); EXPECT_TRUE(frontier_instructions[entry_comp].contains(sub1)); } }
HloSlicerTest_SingleComputationForwardSlice
xla/tools/hlo_slicer_test.cc
void ReduceTupleParameterHelper(HloModule* hlo_module, HloInstruction* tuple_parameter) { // Only handle the case where all the uses are GetTupleElement. for (HloInstruction* user_inst : tuple_parameter->users()) { if (user_inst->opcode() != HloOpcode::kGetTupleElement) { return; } } VLOG(1) << "Parameter instruction to be reduced: " << tuple_parameter->ToString() << " shape size: " << tuple_parameter->shape().tuple_shapes_size() << " users size: " << tuple_parameter->users().size(); // Collect the shapes of the elements that have users. std::vector<Shape> used_shapes; for (HloInstruction* user_inst : tuple_parameter->users()) { used_shapes.push_back(user_inst->shape()); } // Change the shape of `tuple_parameter` to only include the shape of elements // that have users. Shape new_tuple_shape = ShapeUtil::MakeTupleShape(absl::MakeSpan(used_shapes)); tuple_parameter->mutable_shape()->mutable_tuple_shapes()->clear(); for (const auto& shape : used_shapes) { tuple_parameter->mutable_shape()->mutable_tuple_shapes()->push_back(shape); } // Update the tuple index of all of the users of `tuple_parameter`, so that // they index into the right shape. for (int i = 0; i < tuple_parameter->users().size(); ++i) { tuple_parameter->users()[i]->set_tuple_index(i); } // Update HloModule shape. hlo_module->mutable_config().SetComputationLayoutIfExists( hlo_module->entry_computation()->ComputeProgramShape()); } VLOG(1) << "Parameter instruction to be reduced: " void ReduceTupleParameter(HloModule* hlo_module) { // Collect all the parameters instructions of tuple type. std::vector<HloInstruction*> tuple_parameters; for (HloInstruction* parameter : hlo_module->entry_computation()->parameter_instructions()) { if (parameter->shape().IsTuple()) { tuple_parameters.push_back(parameter); } } // For each parameter, invokes `ReduceTupleParameterHelper` to reduce its size // of dimensions. No instruction is added or removed from `hlo_module` during // this process, only shapes of parameter instructions and tuple indices of // their uses are updated. for (HloInstruction* tuple_parameter : tuple_parameters) { ReduceTupleParameterHelper(hlo_module, tuple_parameter); } } HloInstruction* FindShardingInstruction(HloModule* hlo_module) { for (HloComputation* computation : hlo_module->computations()) { for (HloInstruction* instruction : computation->instructions()) { if (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == "Sharding") { CHECK_EQ(instruction->operand_count(), 1); return instruction; } } } return nullptr; } void RemoveSharding(HloModule* hlo_module) { while (HloInstruction* custom_call_instruction = FindShardingInstruction(hlo_module)) { // Replace its uses with its operand. for (HloInstruction* user_instruction : custom_call_instruction->users()) { CHECK_OK(custom_call_instruction->ReplaceUseWith( user_instruction, custom_call_instruction->mutable_operand(0))); } // Detach the custom-call from computation. custom_call_instruction->DetachFromOperandsAndUsers(); CHECK_OK(custom_call_instruction->parent()->RemoveInstruction( custom_call_instruction)); VLOG(1) << "Removed sharding custom-call: " << custom_call_instruction->ToString(); // Verify if the module is still valid. HloVerifier verifier(/*layout_sensitive=*/false, /*allow_mixed_precision=*/true); TF_CHECK_OK(verifier.Run(hlo_module).status()); } } VLOG(1) << "Removed sharding custom-call: " void IntraComputationSlicing( const HloComputation* computation, absl::flat_hash_set<const HloInstruction*>& sliced_instructions, absl::flat_hash_set<const HloInstruction*>& frontier_instructions, bool forward_slice, FrontierSelector frontier_selector, bool ignore_control_dependency) { std::deque<const HloInstruction*> worklist(sliced_instructions.begin(), sliced_instructions.end()); while (!worklist.empty()) { const HloInstruction* inst = worklist.back(); worklist.pop_back(); // If `inst` is at the frontier, bookkeep it, and continue. if (frontier_selector && !frontier_selector(inst)) { frontier_instructions.insert(inst); continue; } // Initialize data-dependent instructions std::vector<HloInstruction*> instructions_to_propagate = forward_slice ? std::vector<HloInstruction*>(inst->users().begin(), inst->users().end()) : std::vector<HloInstruction*>(inst->operands().begin(), inst->operands().end()); // Append control-dependent instructions if necessary if (!ignore_control_dependency) { if (forward_slice) { instructions_to_propagate.insert(instructions_to_propagate.end(), inst->control_successors().begin(), inst->control_successors().end()); } else { instructions_to_propagate.insert(instructions_to_propagate.end(), inst->control_predecessors().begin(), inst->control_predecessors().end()); } } for (auto next_inst : instructions_to_propagate) { if (!sliced_instructions.contains(next_inst)) { worklist.push_front(next_inst); sliced_instructions.insert(next_inst); } } } } SliceOutput SliceModuleHelper( const HloModule* hlo_module, absl::Span<const HloInstruction*> slice_starting_instructions, FrontierSelector frontier_selector, bool ignore_control_dependency, bool forward_slice, bool nearest_common_ancestor_as_root) { // Initialize `sliced_computation_instructions_map`, which keeps track of all // the sliced instructions. absl::flat_hash_map<const HloComputation*, absl::flat_hash_set<const HloInstruction*>> sliced_computation_instructions_map; for (auto inst : slice_starting_instructions) { sliced_computation_instructions_map[inst->parent()].insert(inst); } // Initialize `frontier_computation_instructions_map`. absl::flat_hash_map<const HloComputation*, absl::flat_hash_set<const HloInstruction*>> frontier_computation_instructions_map; // Build call graph. std::unique_ptr<CallGraph> call_graph = CallGraph::Build(hlo_module); // Traverse computations in the post-order(forward slicing) or // reverse post-order(backward slicing) manner, and conduct intra-computation // slicing in that order. // // Post-order guarantees that when computation `a` is visited, all of its // callee computations have been visited, thus all the necessary propagation // to `a` has been conducted (i.e., the sliced caller instruction in `a` has // been marked, which serve as the starting point in // `IntraComputationSlicing`). // // Similarly, reverse post-order guarantees that when computation `a` is // visited, all of its caller computations have been visited, thus its root // instruction has been marked, which serve as the starting point in // `IntraComputationSlicing`. std::vector<HloComputation*> post_order_computations = hlo_module->MakeComputationPostOrder(); std::vector<HloComputation*> computations_to_traverse = forward_slice ? post_order_computations : std::vector<HloComputation*>(post_order_computations.rbegin(), post_order_computations.rend()); // If `nearest_common_ancestor_as_root` is enabled, we compute the // HloComputations that hold the `nearest_common_ancestor` instruction, which // are the stopping points when iterating through `computations_to_traverse`. absl::flat_hash_set<const HloComputation*> nearest_common_ancestor_computations; if (nearest_common_ancestor_as_root) { std::vector<const HloComputation*> starting_computations; for (const auto& [computation, instructions] : sliced_computation_instructions_map) { starting_computations.push_back(computation); } nearest_common_ancestor_computations = call_graph->NearestCommonAncestorComputations(starting_computations); CHECK(!nearest_common_ancestor_computations.empty()); } for (auto computation : computations_to_traverse) { if (sliced_computation_instructions_map.contains(computation)) { auto slicing_starting_instructions = std::vector<const HloInstruction*>( sliced_computation_instructions_map[computation].begin(), sliced_computation_instructions_map[computation].end()); // Do intra-computation slicing, starting from the instructions that has // been inserted in `sliced_computation_instructions_map[computation]`. IntraComputationSlicing( computation, sliced_computation_instructions_map[computation], frontier_computation_instructions_map[computation], forward_slice, frontier_selector, ignore_control_dependency); // The block below propagate the slicing results from the current visiting // computation to the next ones. if (forward_slice) { // Check if the current computation is one of the // `nearest_common_ancestor_computations`. If yes, we find the // `nearest_common_ancestor` as an instruction, and stop here. if (nearest_common_ancestor_as_root && nearest_common_ancestor_computations.contains(computation)) { // We use one of the nearest common ancestor instructions. const HloInstruction* nearest_common_ancestor_instruction = *(call_graph->NearestCommonAncestorInstructions( slicing_starting_instructions)) .begin(); CHECK_NE(nearest_common_ancestor_instruction, nullptr); return SliceOutput{sliced_computation_instructions_map, frontier_computation_instructions_map, nearest_common_ancestor_instruction}; } // Skip propagating if the ROOT instruction of the current computation // is NOT sliced. It is either because (1) the sliced instructions are // actually dead code or (2) `frontier_selector` finds frontier and stop // propagation. The found frontier could be at the root instruction, and // in this case, we stop propagation. if (!sliced_computation_instructions_map[computation].contains( computation->root_instruction()) || frontier_computation_instructions_map[computation].contains( computation->root_instruction())) { continue; } // Continue propagating to successors of the current computation, by // inserting its caller computation into // `sliced_computation_instructions_map`, and inserting the caller // instructions as the starting points for intra-computation slicing. for (auto caller_inst : call_graph->GetComputationCallers(computation)) { sliced_computation_instructions_map[caller_inst->parent()].insert( caller_inst); } } if (!forward_slice) { // Propagate to the callee computation of the current computation // that the sliced instructions invoke, by inserting its callee // computation into `sliced_computation_instructions_map`, and inserting // the root instruction of the callee computation as the starting points // for later intra-computation slicing. for (const auto& callsite : call_graph->GetNode(computation).callsites()) { if (sliced_computation_instructions_map[computation].contains( callsite.instruction())) { for (auto callee : callsite.called_computations()) { sliced_computation_instructions_map[callee].insert( callee->root_instruction()); } } } } } } return SliceOutput{sliced_computation_instructions_map, frontier_computation_instructions_map}; } SliceOutput SliceModule( const HloModule* hlo_module, absl::Span<const HloInstruction*> slice_starting_instructions, FrontierSelector frontier_selector, bool ignore_control_dependency, bool forward_slice, bool nearest_common_ancestor_as_root) { if (forward_slice) { if (!nearest_common_ancestor_as_root) { // Forward slicing with the original root as the root. return SliceModuleHelper(hlo_module, slice_starting_instructions, frontier_selector, ignore_control_dependency, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/false); } else { // Forward slicing with the nearest common ancestor (NCA) as the root. // // Internally, this feature is implemented by the following two steps: // 1. Conducting a pass of forward slicing and looking for the NCA // instruction. We first compute the "NCA computation", which is the // NCA, of the computations that hold the // `slice_starting_instructions`. This computation is achieved by // invoking "NearestCommonAncestorComputations" in the call graph. // Then, when we reach the "NCA computation", we compute the NCA of // the instructions that calls the computations which are on the path // from the `slice_starting_instructions` to this NCA computation. // 2. The slice from step 1 contains some redundant instructions, // because, when we do forward slicing, we do not know the exact path // to the NCA, and there could some nodes that cannot be reached from // the NCA. Therefore, in this step, we conduct a pass of backward // slicing from the NCA and filter out the redundant instructions, by // taking the intersection between the backward slicing results and // the forward slicing results from step 1. // Sanity check. CHECK(forward_slice) << "Option `nearest_common_ancestor_as_root` can " "only be enabled when " "forward slicing"; CHECK((frontier_selector == nullptr)) << "Option `nearest_common_ancestor_as_root` can not be specified " "with `frontier_selector`"; // Forward slicing to identify nearest common ancestor SliceOutput forward_slice_output = SliceModuleHelper(hlo_module, slice_starting_instructions, /*frontier_selector=*/nullptr, ignore_control_dependency, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/true); std::vector<const HloInstruction*> nearest_common_ancestor( {forward_slice_output.nearest_common_ancestor_root()}); CHECK_EQ(nearest_common_ancestor.size(), 1); // Backward slicing from the nearest common ancestor to filter out // the redundant computations/instructions in the sliced result in step 1. SliceOutput backward_slice_output = SliceModuleHelper(hlo_module, /*slice_starting_instructions=*/ absl::MakeSpan(nearest_common_ancestor), /*frontier_selector=*/nullptr, ignore_control_dependency, /*forward_slice=*/false, /*nearest_common_ancestor_as_root=*/false); // Intersect the sliced instructions between forward slicing pass and // backward slicing pass as the new sliced instructions, and return the // new SliceOutput. return SliceOutput{SliceOutput::IntersectSlicedInstructions( forward_slice_output, backward_slice_output), backward_slice_output.frontier_instructions(), forward_slice_output.nearest_common_ancestor_root()}; } } else { // Backward slicing. return SliceModuleHelper(hlo_module, slice_starting_instructions, frontier_selector, ignore_control_dependency, /*forward_slice=*/false, /*nearest_common_ancestor_as_root=*/false); } } std::vector<std::unique_ptr<HloModule>> SliceModuleAndExtract( const HloModule* hlo_module, absl::Span<const HloInstruction*> slice_starting_instructions, const SlicingConfiguration& slicing_configuration) { std::vector<std::unique_ptr<HloModule>> sliced_modules; // Group `slice_starting_instructions` based on `slicing_group` configuration. int slicing_group = slicing_configuration.slicing_group; CHECK(slicing_group >= 1 || slicing_group == -1); std::vector<absl::Span<const HloInstruction*>> grouped_instructions; if (slicing_group == -1) { grouped_instructions = {slice_starting_instructions}; } else { for (int i = 0; i < slice_starting_instructions.size(); i += slicing_group) { // subspan can correctly handel the last group, which may be smaller than // `slicing_group`. grouped_instructions.push_back( slice_starting_instructions.subspan(i, slicing_group)); } } for (const auto& grouped_slice_starting_instructions : grouped_instructions) { // Forward slicing. SliceOutput forward_slice_output; if (slicing_configuration.forward_slicing == SlicingConfiguration::ForwardSlicingConfig::kRoot) { // Slice to the root instruction of the entry computation of `hlo_module`. forward_slice_output = SliceModule( hlo_module, grouped_slice_starting_instructions, /*frontier_selector=*/nullptr, /*ignore_control_dependency=*/false, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/false); } else if (slicing_configuration.forward_slicing == SlicingConfiguration::ForwardSlicingConfig::kNca) { // slice to the nearest common ancestors of // `grouped_slice_starting_instructions` forward_slice_output = SliceModule( hlo_module, grouped_slice_starting_instructions, /*frontier_selector=*/nullptr, /*ignore_control_dependency=*/false, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/true); } VLOG(1) << "[Num of forward sliced insts]: " << forward_slice_output.NumSlicedInstructions(); // Backward slicing. SliceOutput backward_slice_output; if (slicing_configuration.backward_slicing) { backward_slice_output = SliceModule( hlo_module, grouped_slice_starting_instructions, /*frontier_selector=*/nullptr, /*ignore_control_dependency=*/false, /*forward_slice=*/false); } else { // Return the empty SliceOutput if backward slicing is not enabled. backward_slice_output = SliceOutput(); } // Combine forward slicing output and backward slicing output. auto sliced_result = SliceOutput(SliceOutput::UnionSlicedInstructions( forward_slice_output, backward_slice_output)); // Decide Root to start extraction based on `forward_slicing_config`. const HloInstruction* extraction_root = slicing_configuration.forward_slicing == SlicingConfiguration::ForwardSlicingConfig::kNca ? forward_slice_output.nearest_common_ancestor_root() : hlo_module->entry_computation()->root_instruction(); VLOG(1) << "[Root instruction of the sliced module]: " << extraction_root->ToString(); // Exclude the instructions that are not in the slicing results. auto extract_selector = [&sliced_result](const HloInstruction* hlo_inst) { for (const auto& [computation, instructions] : sliced_result.sliced_instructions()) { if (instructions.contains(hlo_inst)) { return true; } } return false; }; // Replace the excluded instructions in the entry computation with zeros. auto replace_type_selector = [](const HloInstruction* hlo_inst) -> ReplaceType { return ReplaceType::kReplaceZeroBroadcast; }; // Extract from the original module. auto extracted_module = ExtractModule(/*instruction=*/extraction_root, /*height=*/-1, /*extract_selector=*/extract_selector, /*replace_type_selector=*/replace_type_selector, /*cross_computation=*/true); // Remove the custom-call to sharding if `remove_sharding` is specified. if (slicing_configuration.remove_sharding) { RemoveSharding(extracted_module.get()); } // Reduce the parameter instructions of tuple shape if // `reduce_tuple_parameter` is specified. if (slicing_configuration.reduce_tuple_parameter) { ReduceTupleParameter(extracted_module.get()); } // Verify if the extracted module (after processing) is valid or not. HloVerifier verifier(/*layout_sensitive=*/false, /*allow_mixed_precision=*/true); TF_CHECK_OK(verifier.Run(extracted_module.get()).status()); sliced_modules.emplace_back(std::move(extracted_module)); } // Return all the sliced modules. CHECK_EQ(sliced_modules.size(), grouped_instructions.size()); return sliced_modules; } VLOG(1) << "[Num of forward sliced insts]: " VLOG(1) << "[Root instruction of the sliced module]: " auto extract_selector = [&sliced_result](const HloInstruction* hlo_inst) { for (const auto& [computation, instructions] : sliced_result.sliced_instructions()) { if (instructions.contains(hlo_inst)) { return true; } } return false; };
#include "xla/tools/hlo_slicer.h" #include <memory> #include <string> #include <utility> #include <vector> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/log/check.h" #include "absl/types/span.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/tests/hlo_test_base.h" #include "tsl/platform/statusor.h" TEST_F(HloSlicerTest, SingleComputationForwardSlice) { const std::string& hlo_string = R"( HloModule axpy_module ENTRY axpy_computation { p.0 = f32[10] parameter(0) p.1 = f32[10] parameter(1) add.0 = f32[10] add(p.0, p.1) alpha = f32[] constant(1) broadcast = f32[10] broadcast(alpha), dimensions={} p.2 = f32[10] parameter(2) y = f32[10] multiply(broadcast, p.2) x = f32[10] subtract(y, add.0) p.3 = f32[10] parameter(3) ROOT add.1 = f32[10] add(x, p.3) } )"; TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> hlo_module, ParseAndReturnVerifiedModule(hlo_string)); auto p2 = FindInstruction(hlo_module.get(), "p.2"); EXPECT_THAT(p2, op::Parameter()); auto p3 = FindInstruction(hlo_module.get(), "p.3"); EXPECT_THAT(p3, op::Parameter()); auto x = FindInstruction(hlo_module.get(), "x"); EXPECT_THAT(x, op::Subtract()); auto y = FindInstruction(hlo_module.get(), "y"); EXPECT_THAT(y, op::Multiply()); auto add0 = FindInstruction(hlo_module.get(), "add.0"); EXPECT_THAT(add0, op::Add()); auto add1 = FindInstruction(hlo_module.get(), "add.1"); EXPECT_THAT(add1, op::Add()); auto entry_comp = FindComputation(hlo_module.get(), "axpy_computation"); EXPECT_NE(entry_comp, nullptr); // Select everything auto hlo_selector = [](const HloInstruction* hlo_inst) -> bool { return true; }; { std::vector<const HloInstruction*> relevant_instructions({p2, x}); auto sliced_result = SliceModule( hlo_module.get(), absl::MakeSpan(relevant_instructions), hlo_selector); auto sliced_instructions = sliced_result.sliced_instructions(); EXPECT_EQ(sliced_instructions.size(), 1); EXPECT_EQ(sliced_instructions[entry_comp].size(), 4); EXPECT_TRUE(sliced_instructions[entry_comp].contains(p2)); EXPECT_TRUE(sliced_instructions[entry_comp].contains(x)); EXPECT_TRUE(sliced_instructions[entry_comp].contains(y)); EXPECT_TRUE(sliced_instructions[entry_comp].contains(add1)); EXPECT_EQ(sliced_result.NumFrontierInstructions(), 0); } { std::vector<const HloInstruction*> relevant_instructions({add0, p3}); auto sliced_result = SliceModule( hlo_module.get(), absl::MakeSpan(relevant_instructions), hlo_selector); auto sliced_instructions = sliced_result.sliced_instructions(); EXPECT_EQ(sliced_instructions.size(), 1); EXPECT_EQ(sliced_instructions[entry_comp].size(), 4); EXPECT_TRUE(sliced_instructions[entry_comp].contains(add0)); EXPECT_TRUE(sliced_instructions[entry_comp].contains(x)); EXPECT_TRUE(sliced_instructions[entry_comp].contains(p3)); EXPECT_TRUE(sliced_instructions[entry_comp].contains(add1)); EXPECT_EQ(sliced_result.NumFrontierInstructions(), 0); } }
HloSlicerTest_TestSliceModuleAndExtract
xla/tools/hlo_slicer_test.cc
void ReduceTupleParameterHelper(HloModule* hlo_module, HloInstruction* tuple_parameter) { // Only handle the case where all the uses are GetTupleElement. for (HloInstruction* user_inst : tuple_parameter->users()) { if (user_inst->opcode() != HloOpcode::kGetTupleElement) { return; } } VLOG(1) << "Parameter instruction to be reduced: " << tuple_parameter->ToString() << " shape size: " << tuple_parameter->shape().tuple_shapes_size() << " users size: " << tuple_parameter->users().size(); // Collect the shapes of the elements that have users. std::vector<Shape> used_shapes; for (HloInstruction* user_inst : tuple_parameter->users()) { used_shapes.push_back(user_inst->shape()); } // Change the shape of `tuple_parameter` to only include the shape of elements // that have users. Shape new_tuple_shape = ShapeUtil::MakeTupleShape(absl::MakeSpan(used_shapes)); tuple_parameter->mutable_shape()->mutable_tuple_shapes()->clear(); for (const auto& shape : used_shapes) { tuple_parameter->mutable_shape()->mutable_tuple_shapes()->push_back(shape); } // Update the tuple index of all of the users of `tuple_parameter`, so that // they index into the right shape. for (int i = 0; i < tuple_parameter->users().size(); ++i) { tuple_parameter->users()[i]->set_tuple_index(i); } // Update HloModule shape. hlo_module->mutable_config().SetComputationLayoutIfExists( hlo_module->entry_computation()->ComputeProgramShape()); } VLOG(1) << "Parameter instruction to be reduced: " void ReduceTupleParameter(HloModule* hlo_module) { // Collect all the parameters instructions of tuple type. std::vector<HloInstruction*> tuple_parameters; for (HloInstruction* parameter : hlo_module->entry_computation()->parameter_instructions()) { if (parameter->shape().IsTuple()) { tuple_parameters.push_back(parameter); } } // For each parameter, invokes `ReduceTupleParameterHelper` to reduce its size // of dimensions. No instruction is added or removed from `hlo_module` during // this process, only shapes of parameter instructions and tuple indices of // their uses are updated. for (HloInstruction* tuple_parameter : tuple_parameters) { ReduceTupleParameterHelper(hlo_module, tuple_parameter); } } HloInstruction* FindShardingInstruction(HloModule* hlo_module) { for (HloComputation* computation : hlo_module->computations()) { for (HloInstruction* instruction : computation->instructions()) { if (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == "Sharding") { CHECK_EQ(instruction->operand_count(), 1); return instruction; } } } return nullptr; } void RemoveSharding(HloModule* hlo_module) { while (HloInstruction* custom_call_instruction = FindShardingInstruction(hlo_module)) { // Replace its uses with its operand. for (HloInstruction* user_instruction : custom_call_instruction->users()) { CHECK_OK(custom_call_instruction->ReplaceUseWith( user_instruction, custom_call_instruction->mutable_operand(0))); } // Detach the custom-call from computation. custom_call_instruction->DetachFromOperandsAndUsers(); CHECK_OK(custom_call_instruction->parent()->RemoveInstruction( custom_call_instruction)); VLOG(1) << "Removed sharding custom-call: " << custom_call_instruction->ToString(); // Verify if the module is still valid. HloVerifier verifier(/*layout_sensitive=*/false, /*allow_mixed_precision=*/true); TF_CHECK_OK(verifier.Run(hlo_module).status()); } } VLOG(1) << "Removed sharding custom-call: " void IntraComputationSlicing( const HloComputation* computation, absl::flat_hash_set<const HloInstruction*>& sliced_instructions, absl::flat_hash_set<const HloInstruction*>& frontier_instructions, bool forward_slice, FrontierSelector frontier_selector, bool ignore_control_dependency) { std::deque<const HloInstruction*> worklist(sliced_instructions.begin(), sliced_instructions.end()); while (!worklist.empty()) { const HloInstruction* inst = worklist.back(); worklist.pop_back(); // If `inst` is at the frontier, bookkeep it, and continue. if (frontier_selector && !frontier_selector(inst)) { frontier_instructions.insert(inst); continue; } // Initialize data-dependent instructions std::vector<HloInstruction*> instructions_to_propagate = forward_slice ? std::vector<HloInstruction*>(inst->users().begin(), inst->users().end()) : std::vector<HloInstruction*>(inst->operands().begin(), inst->operands().end()); // Append control-dependent instructions if necessary if (!ignore_control_dependency) { if (forward_slice) { instructions_to_propagate.insert(instructions_to_propagate.end(), inst->control_successors().begin(), inst->control_successors().end()); } else { instructions_to_propagate.insert(instructions_to_propagate.end(), inst->control_predecessors().begin(), inst->control_predecessors().end()); } } for (auto next_inst : instructions_to_propagate) { if (!sliced_instructions.contains(next_inst)) { worklist.push_front(next_inst); sliced_instructions.insert(next_inst); } } } } SliceOutput SliceModuleHelper( const HloModule* hlo_module, absl::Span<const HloInstruction*> slice_starting_instructions, FrontierSelector frontier_selector, bool ignore_control_dependency, bool forward_slice, bool nearest_common_ancestor_as_root) { // Initialize `sliced_computation_instructions_map`, which keeps track of all // the sliced instructions. absl::flat_hash_map<const HloComputation*, absl::flat_hash_set<const HloInstruction*>> sliced_computation_instructions_map; for (auto inst : slice_starting_instructions) { sliced_computation_instructions_map[inst->parent()].insert(inst); } // Initialize `frontier_computation_instructions_map`. absl::flat_hash_map<const HloComputation*, absl::flat_hash_set<const HloInstruction*>> frontier_computation_instructions_map; // Build call graph. std::unique_ptr<CallGraph> call_graph = CallGraph::Build(hlo_module); // Traverse computations in the post-order(forward slicing) or // reverse post-order(backward slicing) manner, and conduct intra-computation // slicing in that order. // // Post-order guarantees that when computation `a` is visited, all of its // callee computations have been visited, thus all the necessary propagation // to `a` has been conducted (i.e., the sliced caller instruction in `a` has // been marked, which serve as the starting point in // `IntraComputationSlicing`). // // Similarly, reverse post-order guarantees that when computation `a` is // visited, all of its caller computations have been visited, thus its root // instruction has been marked, which serve as the starting point in // `IntraComputationSlicing`. std::vector<HloComputation*> post_order_computations = hlo_module->MakeComputationPostOrder(); std::vector<HloComputation*> computations_to_traverse = forward_slice ? post_order_computations : std::vector<HloComputation*>(post_order_computations.rbegin(), post_order_computations.rend()); // If `nearest_common_ancestor_as_root` is enabled, we compute the // HloComputations that hold the `nearest_common_ancestor` instruction, which // are the stopping points when iterating through `computations_to_traverse`. absl::flat_hash_set<const HloComputation*> nearest_common_ancestor_computations; if (nearest_common_ancestor_as_root) { std::vector<const HloComputation*> starting_computations; for (const auto& [computation, instructions] : sliced_computation_instructions_map) { starting_computations.push_back(computation); } nearest_common_ancestor_computations = call_graph->NearestCommonAncestorComputations(starting_computations); CHECK(!nearest_common_ancestor_computations.empty()); } for (auto computation : computations_to_traverse) { if (sliced_computation_instructions_map.contains(computation)) { auto slicing_starting_instructions = std::vector<const HloInstruction*>( sliced_computation_instructions_map[computation].begin(), sliced_computation_instructions_map[computation].end()); // Do intra-computation slicing, starting from the instructions that has // been inserted in `sliced_computation_instructions_map[computation]`. IntraComputationSlicing( computation, sliced_computation_instructions_map[computation], frontier_computation_instructions_map[computation], forward_slice, frontier_selector, ignore_control_dependency); // The block below propagate the slicing results from the current visiting // computation to the next ones. if (forward_slice) { // Check if the current computation is one of the // `nearest_common_ancestor_computations`. If yes, we find the // `nearest_common_ancestor` as an instruction, and stop here. if (nearest_common_ancestor_as_root && nearest_common_ancestor_computations.contains(computation)) { // We use one of the nearest common ancestor instructions. const HloInstruction* nearest_common_ancestor_instruction = *(call_graph->NearestCommonAncestorInstructions( slicing_starting_instructions)) .begin(); CHECK_NE(nearest_common_ancestor_instruction, nullptr); return SliceOutput{sliced_computation_instructions_map, frontier_computation_instructions_map, nearest_common_ancestor_instruction}; } // Skip propagating if the ROOT instruction of the current computation // is NOT sliced. It is either because (1) the sliced instructions are // actually dead code or (2) `frontier_selector` finds frontier and stop // propagation. The found frontier could be at the root instruction, and // in this case, we stop propagation. if (!sliced_computation_instructions_map[computation].contains( computation->root_instruction()) || frontier_computation_instructions_map[computation].contains( computation->root_instruction())) { continue; } // Continue propagating to successors of the current computation, by // inserting its caller computation into // `sliced_computation_instructions_map`, and inserting the caller // instructions as the starting points for intra-computation slicing. for (auto caller_inst : call_graph->GetComputationCallers(computation)) { sliced_computation_instructions_map[caller_inst->parent()].insert( caller_inst); } } if (!forward_slice) { // Propagate to the callee computation of the current computation // that the sliced instructions invoke, by inserting its callee // computation into `sliced_computation_instructions_map`, and inserting // the root instruction of the callee computation as the starting points // for later intra-computation slicing. for (const auto& callsite : call_graph->GetNode(computation).callsites()) { if (sliced_computation_instructions_map[computation].contains( callsite.instruction())) { for (auto callee : callsite.called_computations()) { sliced_computation_instructions_map[callee].insert( callee->root_instruction()); } } } } } } return SliceOutput{sliced_computation_instructions_map, frontier_computation_instructions_map}; } SliceOutput SliceModule( const HloModule* hlo_module, absl::Span<const HloInstruction*> slice_starting_instructions, FrontierSelector frontier_selector, bool ignore_control_dependency, bool forward_slice, bool nearest_common_ancestor_as_root) { if (forward_slice) { if (!nearest_common_ancestor_as_root) { // Forward slicing with the original root as the root. return SliceModuleHelper(hlo_module, slice_starting_instructions, frontier_selector, ignore_control_dependency, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/false); } else { // Forward slicing with the nearest common ancestor (NCA) as the root. // // Internally, this feature is implemented by the following two steps: // 1. Conducting a pass of forward slicing and looking for the NCA // instruction. We first compute the "NCA computation", which is the // NCA, of the computations that hold the // `slice_starting_instructions`. This computation is achieved by // invoking "NearestCommonAncestorComputations" in the call graph. // Then, when we reach the "NCA computation", we compute the NCA of // the instructions that calls the computations which are on the path // from the `slice_starting_instructions` to this NCA computation. // 2. The slice from step 1 contains some redundant instructions, // because, when we do forward slicing, we do not know the exact path // to the NCA, and there could some nodes that cannot be reached from // the NCA. Therefore, in this step, we conduct a pass of backward // slicing from the NCA and filter out the redundant instructions, by // taking the intersection between the backward slicing results and // the forward slicing results from step 1. // Sanity check. CHECK(forward_slice) << "Option `nearest_common_ancestor_as_root` can " "only be enabled when " "forward slicing"; CHECK((frontier_selector == nullptr)) << "Option `nearest_common_ancestor_as_root` can not be specified " "with `frontier_selector`"; // Forward slicing to identify nearest common ancestor SliceOutput forward_slice_output = SliceModuleHelper(hlo_module, slice_starting_instructions, /*frontier_selector=*/nullptr, ignore_control_dependency, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/true); std::vector<const HloInstruction*> nearest_common_ancestor( {forward_slice_output.nearest_common_ancestor_root()}); CHECK_EQ(nearest_common_ancestor.size(), 1); // Backward slicing from the nearest common ancestor to filter out // the redundant computations/instructions in the sliced result in step 1. SliceOutput backward_slice_output = SliceModuleHelper(hlo_module, /*slice_starting_instructions=*/ absl::MakeSpan(nearest_common_ancestor), /*frontier_selector=*/nullptr, ignore_control_dependency, /*forward_slice=*/false, /*nearest_common_ancestor_as_root=*/false); // Intersect the sliced instructions between forward slicing pass and // backward slicing pass as the new sliced instructions, and return the // new SliceOutput. return SliceOutput{SliceOutput::IntersectSlicedInstructions( forward_slice_output, backward_slice_output), backward_slice_output.frontier_instructions(), forward_slice_output.nearest_common_ancestor_root()}; } } else { // Backward slicing. return SliceModuleHelper(hlo_module, slice_starting_instructions, frontier_selector, ignore_control_dependency, /*forward_slice=*/false, /*nearest_common_ancestor_as_root=*/false); } } std::vector<std::unique_ptr<HloModule>> SliceModuleAndExtract( const HloModule* hlo_module, absl::Span<const HloInstruction*> slice_starting_instructions, const SlicingConfiguration& slicing_configuration) { std::vector<std::unique_ptr<HloModule>> sliced_modules; // Group `slice_starting_instructions` based on `slicing_group` configuration. int slicing_group = slicing_configuration.slicing_group; CHECK(slicing_group >= 1 || slicing_group == -1); std::vector<absl::Span<const HloInstruction*>> grouped_instructions; if (slicing_group == -1) { grouped_instructions = {slice_starting_instructions}; } else { for (int i = 0; i < slice_starting_instructions.size(); i += slicing_group) { // subspan can correctly handel the last group, which may be smaller than // `slicing_group`. grouped_instructions.push_back( slice_starting_instructions.subspan(i, slicing_group)); } } for (const auto& grouped_slice_starting_instructions : grouped_instructions) { // Forward slicing. SliceOutput forward_slice_output; if (slicing_configuration.forward_slicing == SlicingConfiguration::ForwardSlicingConfig::kRoot) { // Slice to the root instruction of the entry computation of `hlo_module`. forward_slice_output = SliceModule( hlo_module, grouped_slice_starting_instructions, /*frontier_selector=*/nullptr, /*ignore_control_dependency=*/false, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/false); } else if (slicing_configuration.forward_slicing == SlicingConfiguration::ForwardSlicingConfig::kNca) { // slice to the nearest common ancestors of // `grouped_slice_starting_instructions` forward_slice_output = SliceModule( hlo_module, grouped_slice_starting_instructions, /*frontier_selector=*/nullptr, /*ignore_control_dependency=*/false, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/true); } VLOG(1) << "[Num of forward sliced insts]: " << forward_slice_output.NumSlicedInstructions(); // Backward slicing. SliceOutput backward_slice_output; if (slicing_configuration.backward_slicing) { backward_slice_output = SliceModule( hlo_module, grouped_slice_starting_instructions, /*frontier_selector=*/nullptr, /*ignore_control_dependency=*/false, /*forward_slice=*/false); } else { // Return the empty SliceOutput if backward slicing is not enabled. backward_slice_output = SliceOutput(); } // Combine forward slicing output and backward slicing output. auto sliced_result = SliceOutput(SliceOutput::UnionSlicedInstructions( forward_slice_output, backward_slice_output)); // Decide Root to start extraction based on `forward_slicing_config`. const HloInstruction* extraction_root = slicing_configuration.forward_slicing == SlicingConfiguration::ForwardSlicingConfig::kNca ? forward_slice_output.nearest_common_ancestor_root() : hlo_module->entry_computation()->root_instruction(); VLOG(1) << "[Root instruction of the sliced module]: " << extraction_root->ToString(); // Exclude the instructions that are not in the slicing results. auto extract_selector = [&sliced_result](const HloInstruction* hlo_inst) { for (const auto& [computation, instructions] : sliced_result.sliced_instructions()) { if (instructions.contains(hlo_inst)) { return true; } } return false; }; // Replace the excluded instructions in the entry computation with zeros. auto replace_type_selector = [](const HloInstruction* hlo_inst) -> ReplaceType { return ReplaceType::kReplaceZeroBroadcast; }; // Extract from the original module. auto extracted_module = ExtractModule(/*instruction=*/extraction_root, /*height=*/-1, /*extract_selector=*/extract_selector, /*replace_type_selector=*/replace_type_selector, /*cross_computation=*/true); // Remove the custom-call to sharding if `remove_sharding` is specified. if (slicing_configuration.remove_sharding) { RemoveSharding(extracted_module.get()); } // Reduce the parameter instructions of tuple shape if // `reduce_tuple_parameter` is specified. if (slicing_configuration.reduce_tuple_parameter) { ReduceTupleParameter(extracted_module.get()); } // Verify if the extracted module (after processing) is valid or not. HloVerifier verifier(/*layout_sensitive=*/false, /*allow_mixed_precision=*/true); TF_CHECK_OK(verifier.Run(extracted_module.get()).status()); sliced_modules.emplace_back(std::move(extracted_module)); } // Return all the sliced modules. CHECK_EQ(sliced_modules.size(), grouped_instructions.size()); return sliced_modules; } VLOG(1) << "[Num of forward sliced insts]: " VLOG(1) << "[Root instruction of the sliced module]: " auto extract_selector = [&sliced_result](const HloInstruction* hlo_inst) { for (const auto& [computation, instructions] : sliced_result.sliced_instructions()) { if (instructions.contains(hlo_inst)) { return true; } } return false; };
#include "xla/tools/hlo_slicer.h" #include <memory> #include <string> #include <utility> #include <vector> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/log/check.h" #include "absl/types/span.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/tests/hlo_test_base.h" #include "tsl/platform/statusor.h" TEST_F(HloSlicerTest, TestSliceModuleAndExtract) { const std::string& hlo_string = R"( HloModule axpy_module calculate_alpha { c.0 = f32[] constant(1) c.1 = f32[] constant(2) ROOT ret.0 = f32[] multiply(c.0, c.1) } calculate_y { c.2 = f32[] constant(2) c.3 = f32[] constant(3) ROOT ret.1 = f32[] add(c.2, c.3) } ENTRY axpy_computation { alpha = f32[] call(), to_apply=calculate_alpha y = f32[] call(), to_apply=calculate_y add.0 = f32[] add(alpha, y) p.0 = f32[] parameter(0) ROOT add.1 = f32[] add(add.0, p.0) } )"; TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> hlo_module, ParseAndReturnVerifiedModule(hlo_string)); auto alpha = FindInstruction(hlo_module.get(), "alpha"); auto y = FindInstruction(hlo_module.get(), "y"); auto add0 = FindInstruction(hlo_module.get(), "add.0"); // slice_starting_instructions: {alpha, y}. // forward_slicing: kNca. // backward_slicing: true. { std::vector<const HloInstruction*> relevant_instructions({alpha, y}); SlicingConfiguration slicing_config = { /*forward_slicing=*/SlicingConfiguration::ForwardSlicingConfig::kNca, /*backward_slicing=*/true}; std::vector<std::unique_ptr<HloModule>> sliced_modules = SliceModuleAndExtract(hlo_module.get(), /*slice_starting_instructions=*/ absl::MakeSpan(relevant_instructions), /*slicing_configuration=*/slicing_config); CHECK_EQ(sliced_modules.size(), 1); auto sliced_module = std::move(sliced_modules[0]); // Test forward slicing: the extracted module should root at `add.0`, which // is the nearest common ancestor of `alpha` and `y`. EXPECT_EQ(sliced_module->entry_computation()->root_instruction()->name(), "add.0"); EXPECT_EQ(sliced_module->entry_computation()->root_instruction()->opcode(), HloOpcode::kAdd); // Test backward slicing: the extracted module should contain all three // computations and all the "leaf instructions". EXPECT_EQ(sliced_module->computation_count(), 3); HloInstruction* c0 = FindInstruction(sliced_module.get(), "c.0"); EXPECT_NE(c0, nullptr); HloInstruction* c1 = FindInstruction(sliced_module.get(), "c.1"); EXPECT_NE(c1, nullptr); HloInstruction* c2 = FindInstruction(sliced_module.get(), "c.2"); EXPECT_NE(c2, nullptr); HloInstruction* c3 = FindInstruction(sliced_module.get(), "c.3"); EXPECT_NE(c3, nullptr); } // slice_starting_instructions: {alpha, y}. // forward_slicing: kRoot. // backward_slicing: true. { std::vector<const HloInstruction*> relevant_instructions({alpha, y}); SlicingConfiguration slicing_config = { /*forward_slicing=*/SlicingConfiguration::ForwardSlicingConfig::kRoot, /*backward_slicing=*/true}; std::vector<std::unique_ptr<HloModule>> sliced_modules = SliceModuleAndExtract(hlo_module.get(), /*slice_starting_instructions=*/ absl::MakeSpan(relevant_instructions), /*slicing_configuration=*/slicing_config); CHECK_EQ(sliced_modules.size(), 1); auto sliced_module = std::move(sliced_modules[0]); // Test forward slicing: the extracted module should root at `add.1`, which // is the original root instruction of entry computation. EXPECT_EQ(sliced_module->entry_computation()->root_instruction()->name(), "add.1"); EXPECT_EQ(sliced_module->entry_computation()->root_instruction()->opcode(), HloOpcode::kAdd); // Test backward slicing: the extracted module should contain all three // computations and all the "leaf instructions". EXPECT_EQ(sliced_module->computation_count(), 3); HloInstruction* c0 = FindInstruction(sliced_module.get(), "c.0"); EXPECT_NE(c0, nullptr); HloInstruction* c1 = FindInstruction(sliced_module.get(), "c.1"); EXPECT_NE(c1, nullptr); HloInstruction* c2 = FindInstruction(sliced_module.get(), "c.2"); EXPECT_NE(c2, nullptr); HloInstruction* c3 = FindInstruction(sliced_module.get(), "c.3"); EXPECT_NE(c3, nullptr); } // slice_starting_instructions: {y}. // forward_slicing: kRoot. // backward_slicing: true. { std::vector<const HloInstruction*> relevant_instructions({y}); SlicingConfiguration slicing_config = { /*forward_slicing=*/SlicingConfiguration::ForwardSlicingConfig::kRoot, /*backward_slicing=*/true}; std::vector<std::unique_ptr<HloModule>> sliced_modules = SliceModuleAndExtract(hlo_module.get(), /*slice_starting_instructions=*/ absl::MakeSpan(relevant_instructions), /*slicing_configuration=*/slicing_config); CHECK_EQ(sliced_modules.size(), 1); auto sliced_module = std::move(sliced_modules[0]); // Test forward slicing: the extracted module should root at `add.1`, which // is the original root instruction of entry computation. EXPECT_EQ(sliced_module->entry_computation()->root_instruction()->name(), "add.1"); EXPECT_EQ(sliced_module->entry_computation()->root_instruction()->opcode(), HloOpcode::kAdd); // Test backward slicing: The computation `axpy_computation` and // `calculate_y` should be included (so as instructions `c2` and `c3`), // while the computation `calculate_alpha` should not be included (so as // instructions `c0` and `c1`). EXPECT_EQ(sliced_module->computation_count(), 2); HloInstruction* c0 = FindInstruction(sliced_module.get(), "c.0"); EXPECT_EQ(c0, nullptr); HloInstruction* c1 = FindInstruction(sliced_module.get(), "c.1"); EXPECT_EQ(c1, nullptr); HloInstruction* c2 = FindInstruction(sliced_module.get(), "c.2"); EXPECT_NE(c2, nullptr); HloInstruction* c3 = FindInstruction(sliced_module.get(), "c.3"); EXPECT_NE(c3, nullptr); } // slice_starting_instructions: {alpha, y}. // forward_slicing: kRoot. // backward_slicing: false. { std::vector<const HloInstruction*> relevant_instructions({add0}); SlicingConfiguration slicing_config = { /*forward_slicing=*/SlicingConfiguration::ForwardSlicingConfig::kRoot, /*backward_slicing=*/false}; std::vector<std::unique_ptr<HloModule>> sliced_modules = SliceModuleAndExtract(hlo_module.get(), /*slice_starting_instructions=*/ absl::MakeSpan(relevant_instructions), /*slicing_configuration=*/slicing_config); CHECK_EQ(sliced_modules.size(), 1); auto sliced_module = std::move(sliced_modules[0]); // Test forward slicing: the extracted module should root at `add.1`, which // is the original root instruction of entry computation. EXPECT_EQ(sliced_module->entry_computation()->root_instruction()->name(), "add.1"); EXPECT_EQ(sliced_module->entry_computation()->root_instruction()->opcode(), HloOpcode::kAdd); // Test backward slicing: The computation `calculate_alpha` and // `calculate_y` should not be included. EXPECT_EQ(sliced_module->computation_count(), 1); } }
HloSlicerTest_TestSliceModuleAndExtractReduceTupleParameter
xla/tools/hlo_slicer_test.cc
void ReduceTupleParameterHelper(HloModule* hlo_module, HloInstruction* tuple_parameter) { // Only handle the case where all the uses are GetTupleElement. for (HloInstruction* user_inst : tuple_parameter->users()) { if (user_inst->opcode() != HloOpcode::kGetTupleElement) { return; } } VLOG(1) << "Parameter instruction to be reduced: " << tuple_parameter->ToString() << " shape size: " << tuple_parameter->shape().tuple_shapes_size() << " users size: " << tuple_parameter->users().size(); // Collect the shapes of the elements that have users. std::vector<Shape> used_shapes; for (HloInstruction* user_inst : tuple_parameter->users()) { used_shapes.push_back(user_inst->shape()); } // Change the shape of `tuple_parameter` to only include the shape of elements // that have users. Shape new_tuple_shape = ShapeUtil::MakeTupleShape(absl::MakeSpan(used_shapes)); tuple_parameter->mutable_shape()->mutable_tuple_shapes()->clear(); for (const auto& shape : used_shapes) { tuple_parameter->mutable_shape()->mutable_tuple_shapes()->push_back(shape); } // Update the tuple index of all of the users of `tuple_parameter`, so that // they index into the right shape. for (int i = 0; i < tuple_parameter->users().size(); ++i) { tuple_parameter->users()[i]->set_tuple_index(i); } // Update HloModule shape. hlo_module->mutable_config().SetComputationLayoutIfExists( hlo_module->entry_computation()->ComputeProgramShape()); } VLOG(1) << "Parameter instruction to be reduced: " void ReduceTupleParameter(HloModule* hlo_module) { // Collect all the parameters instructions of tuple type. std::vector<HloInstruction*> tuple_parameters; for (HloInstruction* parameter : hlo_module->entry_computation()->parameter_instructions()) { if (parameter->shape().IsTuple()) { tuple_parameters.push_back(parameter); } } // For each parameter, invokes `ReduceTupleParameterHelper` to reduce its size // of dimensions. No instruction is added or removed from `hlo_module` during // this process, only shapes of parameter instructions and tuple indices of // their uses are updated. for (HloInstruction* tuple_parameter : tuple_parameters) { ReduceTupleParameterHelper(hlo_module, tuple_parameter); } } HloInstruction* FindShardingInstruction(HloModule* hlo_module) { for (HloComputation* computation : hlo_module->computations()) { for (HloInstruction* instruction : computation->instructions()) { if (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == "Sharding") { CHECK_EQ(instruction->operand_count(), 1); return instruction; } } } return nullptr; } void RemoveSharding(HloModule* hlo_module) { while (HloInstruction* custom_call_instruction = FindShardingInstruction(hlo_module)) { // Replace its uses with its operand. for (HloInstruction* user_instruction : custom_call_instruction->users()) { CHECK_OK(custom_call_instruction->ReplaceUseWith( user_instruction, custom_call_instruction->mutable_operand(0))); } // Detach the custom-call from computation. custom_call_instruction->DetachFromOperandsAndUsers(); CHECK_OK(custom_call_instruction->parent()->RemoveInstruction( custom_call_instruction)); VLOG(1) << "Removed sharding custom-call: " << custom_call_instruction->ToString(); // Verify if the module is still valid. HloVerifier verifier(/*layout_sensitive=*/false, /*allow_mixed_precision=*/true); TF_CHECK_OK(verifier.Run(hlo_module).status()); } } VLOG(1) << "Removed sharding custom-call: " void IntraComputationSlicing( const HloComputation* computation, absl::flat_hash_set<const HloInstruction*>& sliced_instructions, absl::flat_hash_set<const HloInstruction*>& frontier_instructions, bool forward_slice, FrontierSelector frontier_selector, bool ignore_control_dependency) { std::deque<const HloInstruction*> worklist(sliced_instructions.begin(), sliced_instructions.end()); while (!worklist.empty()) { const HloInstruction* inst = worklist.back(); worklist.pop_back(); // If `inst` is at the frontier, bookkeep it, and continue. if (frontier_selector && !frontier_selector(inst)) { frontier_instructions.insert(inst); continue; } // Initialize data-dependent instructions std::vector<HloInstruction*> instructions_to_propagate = forward_slice ? std::vector<HloInstruction*>(inst->users().begin(), inst->users().end()) : std::vector<HloInstruction*>(inst->operands().begin(), inst->operands().end()); // Append control-dependent instructions if necessary if (!ignore_control_dependency) { if (forward_slice) { instructions_to_propagate.insert(instructions_to_propagate.end(), inst->control_successors().begin(), inst->control_successors().end()); } else { instructions_to_propagate.insert(instructions_to_propagate.end(), inst->control_predecessors().begin(), inst->control_predecessors().end()); } } for (auto next_inst : instructions_to_propagate) { if (!sliced_instructions.contains(next_inst)) { worklist.push_front(next_inst); sliced_instructions.insert(next_inst); } } } } SliceOutput SliceModuleHelper( const HloModule* hlo_module, absl::Span<const HloInstruction*> slice_starting_instructions, FrontierSelector frontier_selector, bool ignore_control_dependency, bool forward_slice, bool nearest_common_ancestor_as_root) { // Initialize `sliced_computation_instructions_map`, which keeps track of all // the sliced instructions. absl::flat_hash_map<const HloComputation*, absl::flat_hash_set<const HloInstruction*>> sliced_computation_instructions_map; for (auto inst : slice_starting_instructions) { sliced_computation_instructions_map[inst->parent()].insert(inst); } // Initialize `frontier_computation_instructions_map`. absl::flat_hash_map<const HloComputation*, absl::flat_hash_set<const HloInstruction*>> frontier_computation_instructions_map; // Build call graph. std::unique_ptr<CallGraph> call_graph = CallGraph::Build(hlo_module); // Traverse computations in the post-order(forward slicing) or // reverse post-order(backward slicing) manner, and conduct intra-computation // slicing in that order. // // Post-order guarantees that when computation `a` is visited, all of its // callee computations have been visited, thus all the necessary propagation // to `a` has been conducted (i.e., the sliced caller instruction in `a` has // been marked, which serve as the starting point in // `IntraComputationSlicing`). // // Similarly, reverse post-order guarantees that when computation `a` is // visited, all of its caller computations have been visited, thus its root // instruction has been marked, which serve as the starting point in // `IntraComputationSlicing`. std::vector<HloComputation*> post_order_computations = hlo_module->MakeComputationPostOrder(); std::vector<HloComputation*> computations_to_traverse = forward_slice ? post_order_computations : std::vector<HloComputation*>(post_order_computations.rbegin(), post_order_computations.rend()); // If `nearest_common_ancestor_as_root` is enabled, we compute the // HloComputations that hold the `nearest_common_ancestor` instruction, which // are the stopping points when iterating through `computations_to_traverse`. absl::flat_hash_set<const HloComputation*> nearest_common_ancestor_computations; if (nearest_common_ancestor_as_root) { std::vector<const HloComputation*> starting_computations; for (const auto& [computation, instructions] : sliced_computation_instructions_map) { starting_computations.push_back(computation); } nearest_common_ancestor_computations = call_graph->NearestCommonAncestorComputations(starting_computations); CHECK(!nearest_common_ancestor_computations.empty()); } for (auto computation : computations_to_traverse) { if (sliced_computation_instructions_map.contains(computation)) { auto slicing_starting_instructions = std::vector<const HloInstruction*>( sliced_computation_instructions_map[computation].begin(), sliced_computation_instructions_map[computation].end()); // Do intra-computation slicing, starting from the instructions that has // been inserted in `sliced_computation_instructions_map[computation]`. IntraComputationSlicing( computation, sliced_computation_instructions_map[computation], frontier_computation_instructions_map[computation], forward_slice, frontier_selector, ignore_control_dependency); // The block below propagate the slicing results from the current visiting // computation to the next ones. if (forward_slice) { // Check if the current computation is one of the // `nearest_common_ancestor_computations`. If yes, we find the // `nearest_common_ancestor` as an instruction, and stop here. if (nearest_common_ancestor_as_root && nearest_common_ancestor_computations.contains(computation)) { // We use one of the nearest common ancestor instructions. const HloInstruction* nearest_common_ancestor_instruction = *(call_graph->NearestCommonAncestorInstructions( slicing_starting_instructions)) .begin(); CHECK_NE(nearest_common_ancestor_instruction, nullptr); return SliceOutput{sliced_computation_instructions_map, frontier_computation_instructions_map, nearest_common_ancestor_instruction}; } // Skip propagating if the ROOT instruction of the current computation // is NOT sliced. It is either because (1) the sliced instructions are // actually dead code or (2) `frontier_selector` finds frontier and stop // propagation. The found frontier could be at the root instruction, and // in this case, we stop propagation. if (!sliced_computation_instructions_map[computation].contains( computation->root_instruction()) || frontier_computation_instructions_map[computation].contains( computation->root_instruction())) { continue; } // Continue propagating to successors of the current computation, by // inserting its caller computation into // `sliced_computation_instructions_map`, and inserting the caller // instructions as the starting points for intra-computation slicing. for (auto caller_inst : call_graph->GetComputationCallers(computation)) { sliced_computation_instructions_map[caller_inst->parent()].insert( caller_inst); } } if (!forward_slice) { // Propagate to the callee computation of the current computation // that the sliced instructions invoke, by inserting its callee // computation into `sliced_computation_instructions_map`, and inserting // the root instruction of the callee computation as the starting points // for later intra-computation slicing. for (const auto& callsite : call_graph->GetNode(computation).callsites()) { if (sliced_computation_instructions_map[computation].contains( callsite.instruction())) { for (auto callee : callsite.called_computations()) { sliced_computation_instructions_map[callee].insert( callee->root_instruction()); } } } } } } return SliceOutput{sliced_computation_instructions_map, frontier_computation_instructions_map}; } SliceOutput SliceModule( const HloModule* hlo_module, absl::Span<const HloInstruction*> slice_starting_instructions, FrontierSelector frontier_selector, bool ignore_control_dependency, bool forward_slice, bool nearest_common_ancestor_as_root) { if (forward_slice) { if (!nearest_common_ancestor_as_root) { // Forward slicing with the original root as the root. return SliceModuleHelper(hlo_module, slice_starting_instructions, frontier_selector, ignore_control_dependency, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/false); } else { // Forward slicing with the nearest common ancestor (NCA) as the root. // // Internally, this feature is implemented by the following two steps: // 1. Conducting a pass of forward slicing and looking for the NCA // instruction. We first compute the "NCA computation", which is the // NCA, of the computations that hold the // `slice_starting_instructions`. This computation is achieved by // invoking "NearestCommonAncestorComputations" in the call graph. // Then, when we reach the "NCA computation", we compute the NCA of // the instructions that calls the computations which are on the path // from the `slice_starting_instructions` to this NCA computation. // 2. The slice from step 1 contains some redundant instructions, // because, when we do forward slicing, we do not know the exact path // to the NCA, and there could some nodes that cannot be reached from // the NCA. Therefore, in this step, we conduct a pass of backward // slicing from the NCA and filter out the redundant instructions, by // taking the intersection between the backward slicing results and // the forward slicing results from step 1. // Sanity check. CHECK(forward_slice) << "Option `nearest_common_ancestor_as_root` can " "only be enabled when " "forward slicing"; CHECK((frontier_selector == nullptr)) << "Option `nearest_common_ancestor_as_root` can not be specified " "with `frontier_selector`"; // Forward slicing to identify nearest common ancestor SliceOutput forward_slice_output = SliceModuleHelper(hlo_module, slice_starting_instructions, /*frontier_selector=*/nullptr, ignore_control_dependency, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/true); std::vector<const HloInstruction*> nearest_common_ancestor( {forward_slice_output.nearest_common_ancestor_root()}); CHECK_EQ(nearest_common_ancestor.size(), 1); // Backward slicing from the nearest common ancestor to filter out // the redundant computations/instructions in the sliced result in step 1. SliceOutput backward_slice_output = SliceModuleHelper(hlo_module, /*slice_starting_instructions=*/ absl::MakeSpan(nearest_common_ancestor), /*frontier_selector=*/nullptr, ignore_control_dependency, /*forward_slice=*/false, /*nearest_common_ancestor_as_root=*/false); // Intersect the sliced instructions between forward slicing pass and // backward slicing pass as the new sliced instructions, and return the // new SliceOutput. return SliceOutput{SliceOutput::IntersectSlicedInstructions( forward_slice_output, backward_slice_output), backward_slice_output.frontier_instructions(), forward_slice_output.nearest_common_ancestor_root()}; } } else { // Backward slicing. return SliceModuleHelper(hlo_module, slice_starting_instructions, frontier_selector, ignore_control_dependency, /*forward_slice=*/false, /*nearest_common_ancestor_as_root=*/false); } } std::vector<std::unique_ptr<HloModule>> SliceModuleAndExtract( const HloModule* hlo_module, absl::Span<const HloInstruction*> slice_starting_instructions, const SlicingConfiguration& slicing_configuration) { std::vector<std::unique_ptr<HloModule>> sliced_modules; // Group `slice_starting_instructions` based on `slicing_group` configuration. int slicing_group = slicing_configuration.slicing_group; CHECK(slicing_group >= 1 || slicing_group == -1); std::vector<absl::Span<const HloInstruction*>> grouped_instructions; if (slicing_group == -1) { grouped_instructions = {slice_starting_instructions}; } else { for (int i = 0; i < slice_starting_instructions.size(); i += slicing_group) { // subspan can correctly handel the last group, which may be smaller than // `slicing_group`. grouped_instructions.push_back( slice_starting_instructions.subspan(i, slicing_group)); } } for (const auto& grouped_slice_starting_instructions : grouped_instructions) { // Forward slicing. SliceOutput forward_slice_output; if (slicing_configuration.forward_slicing == SlicingConfiguration::ForwardSlicingConfig::kRoot) { // Slice to the root instruction of the entry computation of `hlo_module`. forward_slice_output = SliceModule( hlo_module, grouped_slice_starting_instructions, /*frontier_selector=*/nullptr, /*ignore_control_dependency=*/false, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/false); } else if (slicing_configuration.forward_slicing == SlicingConfiguration::ForwardSlicingConfig::kNca) { // slice to the nearest common ancestors of // `grouped_slice_starting_instructions` forward_slice_output = SliceModule( hlo_module, grouped_slice_starting_instructions, /*frontier_selector=*/nullptr, /*ignore_control_dependency=*/false, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/true); } VLOG(1) << "[Num of forward sliced insts]: " << forward_slice_output.NumSlicedInstructions(); // Backward slicing. SliceOutput backward_slice_output; if (slicing_configuration.backward_slicing) { backward_slice_output = SliceModule( hlo_module, grouped_slice_starting_instructions, /*frontier_selector=*/nullptr, /*ignore_control_dependency=*/false, /*forward_slice=*/false); } else { // Return the empty SliceOutput if backward slicing is not enabled. backward_slice_output = SliceOutput(); } // Combine forward slicing output and backward slicing output. auto sliced_result = SliceOutput(SliceOutput::UnionSlicedInstructions( forward_slice_output, backward_slice_output)); // Decide Root to start extraction based on `forward_slicing_config`. const HloInstruction* extraction_root = slicing_configuration.forward_slicing == SlicingConfiguration::ForwardSlicingConfig::kNca ? forward_slice_output.nearest_common_ancestor_root() : hlo_module->entry_computation()->root_instruction(); VLOG(1) << "[Root instruction of the sliced module]: " << extraction_root->ToString(); // Exclude the instructions that are not in the slicing results. auto extract_selector = [&sliced_result](const HloInstruction* hlo_inst) { for (const auto& [computation, instructions] : sliced_result.sliced_instructions()) { if (instructions.contains(hlo_inst)) { return true; } } return false; }; // Replace the excluded instructions in the entry computation with zeros. auto replace_type_selector = [](const HloInstruction* hlo_inst) -> ReplaceType { return ReplaceType::kReplaceZeroBroadcast; }; // Extract from the original module. auto extracted_module = ExtractModule(/*instruction=*/extraction_root, /*height=*/-1, /*extract_selector=*/extract_selector, /*replace_type_selector=*/replace_type_selector, /*cross_computation=*/true); // Remove the custom-call to sharding if `remove_sharding` is specified. if (slicing_configuration.remove_sharding) { RemoveSharding(extracted_module.get()); } // Reduce the parameter instructions of tuple shape if // `reduce_tuple_parameter` is specified. if (slicing_configuration.reduce_tuple_parameter) { ReduceTupleParameter(extracted_module.get()); } // Verify if the extracted module (after processing) is valid or not. HloVerifier verifier(/*layout_sensitive=*/false, /*allow_mixed_precision=*/true); TF_CHECK_OK(verifier.Run(extracted_module.get()).status()); sliced_modules.emplace_back(std::move(extracted_module)); } // Return all the sliced modules. CHECK_EQ(sliced_modules.size(), grouped_instructions.size()); return sliced_modules; } VLOG(1) << "[Num of forward sliced insts]: " VLOG(1) << "[Root instruction of the sliced module]: " auto extract_selector = [&sliced_result](const HloInstruction* hlo_inst) { for (const auto& [computation, instructions] : sliced_result.sliced_instructions()) { if (instructions.contains(hlo_inst)) { return true; } } return false; };
#include "xla/tools/hlo_slicer.h" #include <memory> #include <string> #include <utility> #include <vector> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/log/check.h" #include "absl/types/span.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/tests/hlo_test_base.h" #include "tsl/platform/statusor.h" TEST_F(HloSlicerTest, TestSliceModuleAndExtractReduceTupleParameter) { const std::string& hlo_string = R"( HloModule axpy_module ENTRY axpy_computation (p.0: (s32[], s32[3]{0}), p.1: (s32[3]{0}, s32[])) -> s32[] { p.0 = (s32[], s32[3]{0}) parameter(0) gte.0 = s32[] get-tuple-element(p.0), index=0 p.1 = (s32[3]{0}, s32[]) parameter(1) gte.1 = s32[] get-tuple-element(p.1), index=1 ROOT add.0 = s32[] add(gte.0, gte.1) } )"; TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> hlo_module, ParseAndReturnVerifiedModule(hlo_string)); HloInstruction* add_0 = FindInstruction(hlo_module.get(), "add.0"); CHECK_NE(add_0, nullptr); // slice_starting_instructions: {add.0}. // forward_slicing: kRoot. // backward_slicing: true. // remove_sharding: false. // reduce_tuple_parameter: true. { // Slice the whole hlo module and reduce the tuple parameter (p.0 and p.1). std::vector<const HloInstruction*> relevant_instructions({add_0}); SlicingConfiguration slicing_config = { /*forward_slicing=*/SlicingConfiguration::ForwardSlicingConfig::kRoot, /*backward_slicing=*/true, /*remove_sharding=*/false, /*reduce_tuple_parameter=*/true}; std::vector<std::unique_ptr<HloModule>> sliced_modules = SliceModuleAndExtract(hlo_module.get(), /*slice_starting_instructions=*/ absl::MakeSpan(relevant_instructions), /*slicing_configuration=*/slicing_config); EXPECT_EQ(sliced_modules.size(), 1); auto sliced_module = std::move(sliced_modules[0]); // Check that the new p.0 only has one element. HloInstruction* p_0 = FindInstruction(sliced_module.get(), "p.0"); EXPECT_NE(p_0, nullptr); EXPECT_EQ(p_0->shape().tuple_shapes_size(), 1); // Check that the new p.1 only has one element. HloInstruction* p_1 = FindInstruction(sliced_module.get(), "p.1"); EXPECT_NE(p_1, nullptr); EXPECT_EQ(p_1->shape().tuple_shapes_size(), 1); } }
HloSlicerTest_TestSliceModuleAndExtractRemoveSharding
xla/tools/hlo_slicer_test.cc
void ReduceTupleParameterHelper(HloModule* hlo_module, HloInstruction* tuple_parameter) { // Only handle the case where all the uses are GetTupleElement. for (HloInstruction* user_inst : tuple_parameter->users()) { if (user_inst->opcode() != HloOpcode::kGetTupleElement) { return; } } VLOG(1) << "Parameter instruction to be reduced: " << tuple_parameter->ToString() << " shape size: " << tuple_parameter->shape().tuple_shapes_size() << " users size: " << tuple_parameter->users().size(); // Collect the shapes of the elements that have users. std::vector<Shape> used_shapes; for (HloInstruction* user_inst : tuple_parameter->users()) { used_shapes.push_back(user_inst->shape()); } // Change the shape of `tuple_parameter` to only include the shape of elements // that have users. Shape new_tuple_shape = ShapeUtil::MakeTupleShape(absl::MakeSpan(used_shapes)); tuple_parameter->mutable_shape()->mutable_tuple_shapes()->clear(); for (const auto& shape : used_shapes) { tuple_parameter->mutable_shape()->mutable_tuple_shapes()->push_back(shape); } // Update the tuple index of all of the users of `tuple_parameter`, so that // they index into the right shape. for (int i = 0; i < tuple_parameter->users().size(); ++i) { tuple_parameter->users()[i]->set_tuple_index(i); } // Update HloModule shape. hlo_module->mutable_config().SetComputationLayoutIfExists( hlo_module->entry_computation()->ComputeProgramShape()); } VLOG(1) << "Parameter instruction to be reduced: " void ReduceTupleParameter(HloModule* hlo_module) { // Collect all the parameters instructions of tuple type. std::vector<HloInstruction*> tuple_parameters; for (HloInstruction* parameter : hlo_module->entry_computation()->parameter_instructions()) { if (parameter->shape().IsTuple()) { tuple_parameters.push_back(parameter); } } // For each parameter, invokes `ReduceTupleParameterHelper` to reduce its size // of dimensions. No instruction is added or removed from `hlo_module` during // this process, only shapes of parameter instructions and tuple indices of // their uses are updated. for (HloInstruction* tuple_parameter : tuple_parameters) { ReduceTupleParameterHelper(hlo_module, tuple_parameter); } } HloInstruction* FindShardingInstruction(HloModule* hlo_module) { for (HloComputation* computation : hlo_module->computations()) { for (HloInstruction* instruction : computation->instructions()) { if (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == "Sharding") { CHECK_EQ(instruction->operand_count(), 1); return instruction; } } } return nullptr; } void RemoveSharding(HloModule* hlo_module) { while (HloInstruction* custom_call_instruction = FindShardingInstruction(hlo_module)) { // Replace its uses with its operand. for (HloInstruction* user_instruction : custom_call_instruction->users()) { CHECK_OK(custom_call_instruction->ReplaceUseWith( user_instruction, custom_call_instruction->mutable_operand(0))); } // Detach the custom-call from computation. custom_call_instruction->DetachFromOperandsAndUsers(); CHECK_OK(custom_call_instruction->parent()->RemoveInstruction( custom_call_instruction)); VLOG(1) << "Removed sharding custom-call: " << custom_call_instruction->ToString(); // Verify if the module is still valid. HloVerifier verifier(/*layout_sensitive=*/false, /*allow_mixed_precision=*/true); TF_CHECK_OK(verifier.Run(hlo_module).status()); } } VLOG(1) << "Removed sharding custom-call: " void IntraComputationSlicing( const HloComputation* computation, absl::flat_hash_set<const HloInstruction*>& sliced_instructions, absl::flat_hash_set<const HloInstruction*>& frontier_instructions, bool forward_slice, FrontierSelector frontier_selector, bool ignore_control_dependency) { std::deque<const HloInstruction*> worklist(sliced_instructions.begin(), sliced_instructions.end()); while (!worklist.empty()) { const HloInstruction* inst = worklist.back(); worklist.pop_back(); // If `inst` is at the frontier, bookkeep it, and continue. if (frontier_selector && !frontier_selector(inst)) { frontier_instructions.insert(inst); continue; } // Initialize data-dependent instructions std::vector<HloInstruction*> instructions_to_propagate = forward_slice ? std::vector<HloInstruction*>(inst->users().begin(), inst->users().end()) : std::vector<HloInstruction*>(inst->operands().begin(), inst->operands().end()); // Append control-dependent instructions if necessary if (!ignore_control_dependency) { if (forward_slice) { instructions_to_propagate.insert(instructions_to_propagate.end(), inst->control_successors().begin(), inst->control_successors().end()); } else { instructions_to_propagate.insert(instructions_to_propagate.end(), inst->control_predecessors().begin(), inst->control_predecessors().end()); } } for (auto next_inst : instructions_to_propagate) { if (!sliced_instructions.contains(next_inst)) { worklist.push_front(next_inst); sliced_instructions.insert(next_inst); } } } } SliceOutput SliceModuleHelper( const HloModule* hlo_module, absl::Span<const HloInstruction*> slice_starting_instructions, FrontierSelector frontier_selector, bool ignore_control_dependency, bool forward_slice, bool nearest_common_ancestor_as_root) { // Initialize `sliced_computation_instructions_map`, which keeps track of all // the sliced instructions. absl::flat_hash_map<const HloComputation*, absl::flat_hash_set<const HloInstruction*>> sliced_computation_instructions_map; for (auto inst : slice_starting_instructions) { sliced_computation_instructions_map[inst->parent()].insert(inst); } // Initialize `frontier_computation_instructions_map`. absl::flat_hash_map<const HloComputation*, absl::flat_hash_set<const HloInstruction*>> frontier_computation_instructions_map; // Build call graph. std::unique_ptr<CallGraph> call_graph = CallGraph::Build(hlo_module); // Traverse computations in the post-order(forward slicing) or // reverse post-order(backward slicing) manner, and conduct intra-computation // slicing in that order. // // Post-order guarantees that when computation `a` is visited, all of its // callee computations have been visited, thus all the necessary propagation // to `a` has been conducted (i.e., the sliced caller instruction in `a` has // been marked, which serve as the starting point in // `IntraComputationSlicing`). // // Similarly, reverse post-order guarantees that when computation `a` is // visited, all of its caller computations have been visited, thus its root // instruction has been marked, which serve as the starting point in // `IntraComputationSlicing`. std::vector<HloComputation*> post_order_computations = hlo_module->MakeComputationPostOrder(); std::vector<HloComputation*> computations_to_traverse = forward_slice ? post_order_computations : std::vector<HloComputation*>(post_order_computations.rbegin(), post_order_computations.rend()); // If `nearest_common_ancestor_as_root` is enabled, we compute the // HloComputations that hold the `nearest_common_ancestor` instruction, which // are the stopping points when iterating through `computations_to_traverse`. absl::flat_hash_set<const HloComputation*> nearest_common_ancestor_computations; if (nearest_common_ancestor_as_root) { std::vector<const HloComputation*> starting_computations; for (const auto& [computation, instructions] : sliced_computation_instructions_map) { starting_computations.push_back(computation); } nearest_common_ancestor_computations = call_graph->NearestCommonAncestorComputations(starting_computations); CHECK(!nearest_common_ancestor_computations.empty()); } for (auto computation : computations_to_traverse) { if (sliced_computation_instructions_map.contains(computation)) { auto slicing_starting_instructions = std::vector<const HloInstruction*>( sliced_computation_instructions_map[computation].begin(), sliced_computation_instructions_map[computation].end()); // Do intra-computation slicing, starting from the instructions that has // been inserted in `sliced_computation_instructions_map[computation]`. IntraComputationSlicing( computation, sliced_computation_instructions_map[computation], frontier_computation_instructions_map[computation], forward_slice, frontier_selector, ignore_control_dependency); // The block below propagate the slicing results from the current visiting // computation to the next ones. if (forward_slice) { // Check if the current computation is one of the // `nearest_common_ancestor_computations`. If yes, we find the // `nearest_common_ancestor` as an instruction, and stop here. if (nearest_common_ancestor_as_root && nearest_common_ancestor_computations.contains(computation)) { // We use one of the nearest common ancestor instructions. const HloInstruction* nearest_common_ancestor_instruction = *(call_graph->NearestCommonAncestorInstructions( slicing_starting_instructions)) .begin(); CHECK_NE(nearest_common_ancestor_instruction, nullptr); return SliceOutput{sliced_computation_instructions_map, frontier_computation_instructions_map, nearest_common_ancestor_instruction}; } // Skip propagating if the ROOT instruction of the current computation // is NOT sliced. It is either because (1) the sliced instructions are // actually dead code or (2) `frontier_selector` finds frontier and stop // propagation. The found frontier could be at the root instruction, and // in this case, we stop propagation. if (!sliced_computation_instructions_map[computation].contains( computation->root_instruction()) || frontier_computation_instructions_map[computation].contains( computation->root_instruction())) { continue; } // Continue propagating to successors of the current computation, by // inserting its caller computation into // `sliced_computation_instructions_map`, and inserting the caller // instructions as the starting points for intra-computation slicing. for (auto caller_inst : call_graph->GetComputationCallers(computation)) { sliced_computation_instructions_map[caller_inst->parent()].insert( caller_inst); } } if (!forward_slice) { // Propagate to the callee computation of the current computation // that the sliced instructions invoke, by inserting its callee // computation into `sliced_computation_instructions_map`, and inserting // the root instruction of the callee computation as the starting points // for later intra-computation slicing. for (const auto& callsite : call_graph->GetNode(computation).callsites()) { if (sliced_computation_instructions_map[computation].contains( callsite.instruction())) { for (auto callee : callsite.called_computations()) { sliced_computation_instructions_map[callee].insert( callee->root_instruction()); } } } } } } return SliceOutput{sliced_computation_instructions_map, frontier_computation_instructions_map}; } SliceOutput SliceModule( const HloModule* hlo_module, absl::Span<const HloInstruction*> slice_starting_instructions, FrontierSelector frontier_selector, bool ignore_control_dependency, bool forward_slice, bool nearest_common_ancestor_as_root) { if (forward_slice) { if (!nearest_common_ancestor_as_root) { // Forward slicing with the original root as the root. return SliceModuleHelper(hlo_module, slice_starting_instructions, frontier_selector, ignore_control_dependency, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/false); } else { // Forward slicing with the nearest common ancestor (NCA) as the root. // // Internally, this feature is implemented by the following two steps: // 1. Conducting a pass of forward slicing and looking for the NCA // instruction. We first compute the "NCA computation", which is the // NCA, of the computations that hold the // `slice_starting_instructions`. This computation is achieved by // invoking "NearestCommonAncestorComputations" in the call graph. // Then, when we reach the "NCA computation", we compute the NCA of // the instructions that calls the computations which are on the path // from the `slice_starting_instructions` to this NCA computation. // 2. The slice from step 1 contains some redundant instructions, // because, when we do forward slicing, we do not know the exact path // to the NCA, and there could some nodes that cannot be reached from // the NCA. Therefore, in this step, we conduct a pass of backward // slicing from the NCA and filter out the redundant instructions, by // taking the intersection between the backward slicing results and // the forward slicing results from step 1. // Sanity check. CHECK(forward_slice) << "Option `nearest_common_ancestor_as_root` can " "only be enabled when " "forward slicing"; CHECK((frontier_selector == nullptr)) << "Option `nearest_common_ancestor_as_root` can not be specified " "with `frontier_selector`"; // Forward slicing to identify nearest common ancestor SliceOutput forward_slice_output = SliceModuleHelper(hlo_module, slice_starting_instructions, /*frontier_selector=*/nullptr, ignore_control_dependency, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/true); std::vector<const HloInstruction*> nearest_common_ancestor( {forward_slice_output.nearest_common_ancestor_root()}); CHECK_EQ(nearest_common_ancestor.size(), 1); // Backward slicing from the nearest common ancestor to filter out // the redundant computations/instructions in the sliced result in step 1. SliceOutput backward_slice_output = SliceModuleHelper(hlo_module, /*slice_starting_instructions=*/ absl::MakeSpan(nearest_common_ancestor), /*frontier_selector=*/nullptr, ignore_control_dependency, /*forward_slice=*/false, /*nearest_common_ancestor_as_root=*/false); // Intersect the sliced instructions between forward slicing pass and // backward slicing pass as the new sliced instructions, and return the // new SliceOutput. return SliceOutput{SliceOutput::IntersectSlicedInstructions( forward_slice_output, backward_slice_output), backward_slice_output.frontier_instructions(), forward_slice_output.nearest_common_ancestor_root()}; } } else { // Backward slicing. return SliceModuleHelper(hlo_module, slice_starting_instructions, frontier_selector, ignore_control_dependency, /*forward_slice=*/false, /*nearest_common_ancestor_as_root=*/false); } } std::vector<std::unique_ptr<HloModule>> SliceModuleAndExtract( const HloModule* hlo_module, absl::Span<const HloInstruction*> slice_starting_instructions, const SlicingConfiguration& slicing_configuration) { std::vector<std::unique_ptr<HloModule>> sliced_modules; // Group `slice_starting_instructions` based on `slicing_group` configuration. int slicing_group = slicing_configuration.slicing_group; CHECK(slicing_group >= 1 || slicing_group == -1); std::vector<absl::Span<const HloInstruction*>> grouped_instructions; if (slicing_group == -1) { grouped_instructions = {slice_starting_instructions}; } else { for (int i = 0; i < slice_starting_instructions.size(); i += slicing_group) { // subspan can correctly handel the last group, which may be smaller than // `slicing_group`. grouped_instructions.push_back( slice_starting_instructions.subspan(i, slicing_group)); } } for (const auto& grouped_slice_starting_instructions : grouped_instructions) { // Forward slicing. SliceOutput forward_slice_output; if (slicing_configuration.forward_slicing == SlicingConfiguration::ForwardSlicingConfig::kRoot) { // Slice to the root instruction of the entry computation of `hlo_module`. forward_slice_output = SliceModule( hlo_module, grouped_slice_starting_instructions, /*frontier_selector=*/nullptr, /*ignore_control_dependency=*/false, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/false); } else if (slicing_configuration.forward_slicing == SlicingConfiguration::ForwardSlicingConfig::kNca) { // slice to the nearest common ancestors of // `grouped_slice_starting_instructions` forward_slice_output = SliceModule( hlo_module, grouped_slice_starting_instructions, /*frontier_selector=*/nullptr, /*ignore_control_dependency=*/false, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/true); } VLOG(1) << "[Num of forward sliced insts]: " << forward_slice_output.NumSlicedInstructions(); // Backward slicing. SliceOutput backward_slice_output; if (slicing_configuration.backward_slicing) { backward_slice_output = SliceModule( hlo_module, grouped_slice_starting_instructions, /*frontier_selector=*/nullptr, /*ignore_control_dependency=*/false, /*forward_slice=*/false); } else { // Return the empty SliceOutput if backward slicing is not enabled. backward_slice_output = SliceOutput(); } // Combine forward slicing output and backward slicing output. auto sliced_result = SliceOutput(SliceOutput::UnionSlicedInstructions( forward_slice_output, backward_slice_output)); // Decide Root to start extraction based on `forward_slicing_config`. const HloInstruction* extraction_root = slicing_configuration.forward_slicing == SlicingConfiguration::ForwardSlicingConfig::kNca ? forward_slice_output.nearest_common_ancestor_root() : hlo_module->entry_computation()->root_instruction(); VLOG(1) << "[Root instruction of the sliced module]: " << extraction_root->ToString(); // Exclude the instructions that are not in the slicing results. auto extract_selector = [&sliced_result](const HloInstruction* hlo_inst) { for (const auto& [computation, instructions] : sliced_result.sliced_instructions()) { if (instructions.contains(hlo_inst)) { return true; } } return false; }; // Replace the excluded instructions in the entry computation with zeros. auto replace_type_selector = [](const HloInstruction* hlo_inst) -> ReplaceType { return ReplaceType::kReplaceZeroBroadcast; }; // Extract from the original module. auto extracted_module = ExtractModule(/*instruction=*/extraction_root, /*height=*/-1, /*extract_selector=*/extract_selector, /*replace_type_selector=*/replace_type_selector, /*cross_computation=*/true); // Remove the custom-call to sharding if `remove_sharding` is specified. if (slicing_configuration.remove_sharding) { RemoveSharding(extracted_module.get()); } // Reduce the parameter instructions of tuple shape if // `reduce_tuple_parameter` is specified. if (slicing_configuration.reduce_tuple_parameter) { ReduceTupleParameter(extracted_module.get()); } // Verify if the extracted module (after processing) is valid or not. HloVerifier verifier(/*layout_sensitive=*/false, /*allow_mixed_precision=*/true); TF_CHECK_OK(verifier.Run(extracted_module.get()).status()); sliced_modules.emplace_back(std::move(extracted_module)); } // Return all the sliced modules. CHECK_EQ(sliced_modules.size(), grouped_instructions.size()); return sliced_modules; } VLOG(1) << "[Num of forward sliced insts]: " VLOG(1) << "[Root instruction of the sliced module]: " auto extract_selector = [&sliced_result](const HloInstruction* hlo_inst) { for (const auto& [computation, instructions] : sliced_result.sliced_instructions()) { if (instructions.contains(hlo_inst)) { return true; } } return false; };
#include "xla/tools/hlo_slicer.h" #include <memory> #include <string> #include <utility> #include <vector> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/log/check.h" #include "absl/types/span.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/tests/hlo_test_base.h" #include "tsl/platform/statusor.h" TEST_F(HloSlicerTest, TestSliceModuleAndExtractRemoveSharding) { const std::string& hlo_string = R"( HloModule axpy_module ENTRY axpy_computation { %constant.39733 = bf16[] constant(111) %broadcast.39734 = bf16[8,1,12288]{2,1,0} broadcast(bf16[] %constant.39733), dimensions={} %multiply.39766 = bf16[8,1,12288]{2,1,0} multiply(bf16[8,1,12288]{2,1,0} %broadcast.39734, bf16[8,1,12288]{2,1,0} %broadcast.39734) %custom-call.39767 = bf16[8,1,12288]{2,1,0} custom-call(bf16[8,1,12288]{2,1,0} %multiply.39766), custom_call_target="Sharding", sharding={replicated} ROOT %add.39786 = bf16[8,1,12288]{2,1,0} add(bf16[8,1,12288]{2,1,0} %custom-call.39767, bf16[8,1,12288]{2,1,0} %custom-call.39767) } )"; TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> hlo_module, ParseAndReturnVerifiedModule(hlo_string)); HloInstruction* multiply_39766 = FindInstruction(hlo_module.get(), "multiply.39766"); // slice_starting_instructions: {multiply_39766 }. // forward_slicing: kRoot. // backward_slicing: false. // remove_sharding: true. { std::vector<const HloInstruction*> relevant_instructions({multiply_39766}); SlicingConfiguration slicing_config = { /*forward_slicing=*/SlicingConfiguration::ForwardSlicingConfig::kRoot, /*backward_slicing=*/false, /*remove_sharding=*/true}; std::vector<std::unique_ptr<HloModule>> sliced_modules = SliceModuleAndExtract(hlo_module.get(), /*slice_starting_instructions=*/ absl::MakeSpan(relevant_instructions), /*slicing_configuration=*/slicing_config); EXPECT_EQ(sliced_modules.size(), 1); auto sliced_module = std::move(sliced_modules[0]); // Test if the custom-call to sharding is removed. for (HloInstruction* instruction : sliced_module->entry_computation()->instructions()) { EXPECT_NE(instruction->opcode(), HloOpcode::kCustomCall); } // Check that both the operands of %add.39786 are %multiply.39766. for (HloInstruction* instruction : sliced_module->entry_computation()->root_instruction()->operands()) { EXPECT_EQ(instruction->name(), "multiply.39766"); } } }
HloSlicerTest_TestSliceModuleAndExtractSlicingGroup
xla/tools/hlo_slicer_test.cc
void ReduceTupleParameterHelper(HloModule* hlo_module, HloInstruction* tuple_parameter) { // Only handle the case where all the uses are GetTupleElement. for (HloInstruction* user_inst : tuple_parameter->users()) { if (user_inst->opcode() != HloOpcode::kGetTupleElement) { return; } } VLOG(1) << "Parameter instruction to be reduced: " << tuple_parameter->ToString() << " shape size: " << tuple_parameter->shape().tuple_shapes_size() << " users size: " << tuple_parameter->users().size(); // Collect the shapes of the elements that have users. std::vector<Shape> used_shapes; for (HloInstruction* user_inst : tuple_parameter->users()) { used_shapes.push_back(user_inst->shape()); } // Change the shape of `tuple_parameter` to only include the shape of elements // that have users. Shape new_tuple_shape = ShapeUtil::MakeTupleShape(absl::MakeSpan(used_shapes)); tuple_parameter->mutable_shape()->mutable_tuple_shapes()->clear(); for (const auto& shape : used_shapes) { tuple_parameter->mutable_shape()->mutable_tuple_shapes()->push_back(shape); } // Update the tuple index of all of the users of `tuple_parameter`, so that // they index into the right shape. for (int i = 0; i < tuple_parameter->users().size(); ++i) { tuple_parameter->users()[i]->set_tuple_index(i); } // Update HloModule shape. hlo_module->mutable_config().SetComputationLayoutIfExists( hlo_module->entry_computation()->ComputeProgramShape()); } VLOG(1) << "Parameter instruction to be reduced: " void ReduceTupleParameter(HloModule* hlo_module) { // Collect all the parameters instructions of tuple type. std::vector<HloInstruction*> tuple_parameters; for (HloInstruction* parameter : hlo_module->entry_computation()->parameter_instructions()) { if (parameter->shape().IsTuple()) { tuple_parameters.push_back(parameter); } } // For each parameter, invokes `ReduceTupleParameterHelper` to reduce its size // of dimensions. No instruction is added or removed from `hlo_module` during // this process, only shapes of parameter instructions and tuple indices of // their uses are updated. for (HloInstruction* tuple_parameter : tuple_parameters) { ReduceTupleParameterHelper(hlo_module, tuple_parameter); } } HloInstruction* FindShardingInstruction(HloModule* hlo_module) { for (HloComputation* computation : hlo_module->computations()) { for (HloInstruction* instruction : computation->instructions()) { if (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == "Sharding") { CHECK_EQ(instruction->operand_count(), 1); return instruction; } } } return nullptr; } void RemoveSharding(HloModule* hlo_module) { while (HloInstruction* custom_call_instruction = FindShardingInstruction(hlo_module)) { // Replace its uses with its operand. for (HloInstruction* user_instruction : custom_call_instruction->users()) { CHECK_OK(custom_call_instruction->ReplaceUseWith( user_instruction, custom_call_instruction->mutable_operand(0))); } // Detach the custom-call from computation. custom_call_instruction->DetachFromOperandsAndUsers(); CHECK_OK(custom_call_instruction->parent()->RemoveInstruction( custom_call_instruction)); VLOG(1) << "Removed sharding custom-call: " << custom_call_instruction->ToString(); // Verify if the module is still valid. HloVerifier verifier(/*layout_sensitive=*/false, /*allow_mixed_precision=*/true); TF_CHECK_OK(verifier.Run(hlo_module).status()); } } VLOG(1) << "Removed sharding custom-call: " void IntraComputationSlicing( const HloComputation* computation, absl::flat_hash_set<const HloInstruction*>& sliced_instructions, absl::flat_hash_set<const HloInstruction*>& frontier_instructions, bool forward_slice, FrontierSelector frontier_selector, bool ignore_control_dependency) { std::deque<const HloInstruction*> worklist(sliced_instructions.begin(), sliced_instructions.end()); while (!worklist.empty()) { const HloInstruction* inst = worklist.back(); worklist.pop_back(); // If `inst` is at the frontier, bookkeep it, and continue. if (frontier_selector && !frontier_selector(inst)) { frontier_instructions.insert(inst); continue; } // Initialize data-dependent instructions std::vector<HloInstruction*> instructions_to_propagate = forward_slice ? std::vector<HloInstruction*>(inst->users().begin(), inst->users().end()) : std::vector<HloInstruction*>(inst->operands().begin(), inst->operands().end()); // Append control-dependent instructions if necessary if (!ignore_control_dependency) { if (forward_slice) { instructions_to_propagate.insert(instructions_to_propagate.end(), inst->control_successors().begin(), inst->control_successors().end()); } else { instructions_to_propagate.insert(instructions_to_propagate.end(), inst->control_predecessors().begin(), inst->control_predecessors().end()); } } for (auto next_inst : instructions_to_propagate) { if (!sliced_instructions.contains(next_inst)) { worklist.push_front(next_inst); sliced_instructions.insert(next_inst); } } } } SliceOutput SliceModuleHelper( const HloModule* hlo_module, absl::Span<const HloInstruction*> slice_starting_instructions, FrontierSelector frontier_selector, bool ignore_control_dependency, bool forward_slice, bool nearest_common_ancestor_as_root) { // Initialize `sliced_computation_instructions_map`, which keeps track of all // the sliced instructions. absl::flat_hash_map<const HloComputation*, absl::flat_hash_set<const HloInstruction*>> sliced_computation_instructions_map; for (auto inst : slice_starting_instructions) { sliced_computation_instructions_map[inst->parent()].insert(inst); } // Initialize `frontier_computation_instructions_map`. absl::flat_hash_map<const HloComputation*, absl::flat_hash_set<const HloInstruction*>> frontier_computation_instructions_map; // Build call graph. std::unique_ptr<CallGraph> call_graph = CallGraph::Build(hlo_module); // Traverse computations in the post-order(forward slicing) or // reverse post-order(backward slicing) manner, and conduct intra-computation // slicing in that order. // // Post-order guarantees that when computation `a` is visited, all of its // callee computations have been visited, thus all the necessary propagation // to `a` has been conducted (i.e., the sliced caller instruction in `a` has // been marked, which serve as the starting point in // `IntraComputationSlicing`). // // Similarly, reverse post-order guarantees that when computation `a` is // visited, all of its caller computations have been visited, thus its root // instruction has been marked, which serve as the starting point in // `IntraComputationSlicing`. std::vector<HloComputation*> post_order_computations = hlo_module->MakeComputationPostOrder(); std::vector<HloComputation*> computations_to_traverse = forward_slice ? post_order_computations : std::vector<HloComputation*>(post_order_computations.rbegin(), post_order_computations.rend()); // If `nearest_common_ancestor_as_root` is enabled, we compute the // HloComputations that hold the `nearest_common_ancestor` instruction, which // are the stopping points when iterating through `computations_to_traverse`. absl::flat_hash_set<const HloComputation*> nearest_common_ancestor_computations; if (nearest_common_ancestor_as_root) { std::vector<const HloComputation*> starting_computations; for (const auto& [computation, instructions] : sliced_computation_instructions_map) { starting_computations.push_back(computation); } nearest_common_ancestor_computations = call_graph->NearestCommonAncestorComputations(starting_computations); CHECK(!nearest_common_ancestor_computations.empty()); } for (auto computation : computations_to_traverse) { if (sliced_computation_instructions_map.contains(computation)) { auto slicing_starting_instructions = std::vector<const HloInstruction*>( sliced_computation_instructions_map[computation].begin(), sliced_computation_instructions_map[computation].end()); // Do intra-computation slicing, starting from the instructions that has // been inserted in `sliced_computation_instructions_map[computation]`. IntraComputationSlicing( computation, sliced_computation_instructions_map[computation], frontier_computation_instructions_map[computation], forward_slice, frontier_selector, ignore_control_dependency); // The block below propagate the slicing results from the current visiting // computation to the next ones. if (forward_slice) { // Check if the current computation is one of the // `nearest_common_ancestor_computations`. If yes, we find the // `nearest_common_ancestor` as an instruction, and stop here. if (nearest_common_ancestor_as_root && nearest_common_ancestor_computations.contains(computation)) { // We use one of the nearest common ancestor instructions. const HloInstruction* nearest_common_ancestor_instruction = *(call_graph->NearestCommonAncestorInstructions( slicing_starting_instructions)) .begin(); CHECK_NE(nearest_common_ancestor_instruction, nullptr); return SliceOutput{sliced_computation_instructions_map, frontier_computation_instructions_map, nearest_common_ancestor_instruction}; } // Skip propagating if the ROOT instruction of the current computation // is NOT sliced. It is either because (1) the sliced instructions are // actually dead code or (2) `frontier_selector` finds frontier and stop // propagation. The found frontier could be at the root instruction, and // in this case, we stop propagation. if (!sliced_computation_instructions_map[computation].contains( computation->root_instruction()) || frontier_computation_instructions_map[computation].contains( computation->root_instruction())) { continue; } // Continue propagating to successors of the current computation, by // inserting its caller computation into // `sliced_computation_instructions_map`, and inserting the caller // instructions as the starting points for intra-computation slicing. for (auto caller_inst : call_graph->GetComputationCallers(computation)) { sliced_computation_instructions_map[caller_inst->parent()].insert( caller_inst); } } if (!forward_slice) { // Propagate to the callee computation of the current computation // that the sliced instructions invoke, by inserting its callee // computation into `sliced_computation_instructions_map`, and inserting // the root instruction of the callee computation as the starting points // for later intra-computation slicing. for (const auto& callsite : call_graph->GetNode(computation).callsites()) { if (sliced_computation_instructions_map[computation].contains( callsite.instruction())) { for (auto callee : callsite.called_computations()) { sliced_computation_instructions_map[callee].insert( callee->root_instruction()); } } } } } } return SliceOutput{sliced_computation_instructions_map, frontier_computation_instructions_map}; } SliceOutput SliceModule( const HloModule* hlo_module, absl::Span<const HloInstruction*> slice_starting_instructions, FrontierSelector frontier_selector, bool ignore_control_dependency, bool forward_slice, bool nearest_common_ancestor_as_root) { if (forward_slice) { if (!nearest_common_ancestor_as_root) { // Forward slicing with the original root as the root. return SliceModuleHelper(hlo_module, slice_starting_instructions, frontier_selector, ignore_control_dependency, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/false); } else { // Forward slicing with the nearest common ancestor (NCA) as the root. // // Internally, this feature is implemented by the following two steps: // 1. Conducting a pass of forward slicing and looking for the NCA // instruction. We first compute the "NCA computation", which is the // NCA, of the computations that hold the // `slice_starting_instructions`. This computation is achieved by // invoking "NearestCommonAncestorComputations" in the call graph. // Then, when we reach the "NCA computation", we compute the NCA of // the instructions that calls the computations which are on the path // from the `slice_starting_instructions` to this NCA computation. // 2. The slice from step 1 contains some redundant instructions, // because, when we do forward slicing, we do not know the exact path // to the NCA, and there could some nodes that cannot be reached from // the NCA. Therefore, in this step, we conduct a pass of backward // slicing from the NCA and filter out the redundant instructions, by // taking the intersection between the backward slicing results and // the forward slicing results from step 1. // Sanity check. CHECK(forward_slice) << "Option `nearest_common_ancestor_as_root` can " "only be enabled when " "forward slicing"; CHECK((frontier_selector == nullptr)) << "Option `nearest_common_ancestor_as_root` can not be specified " "with `frontier_selector`"; // Forward slicing to identify nearest common ancestor SliceOutput forward_slice_output = SliceModuleHelper(hlo_module, slice_starting_instructions, /*frontier_selector=*/nullptr, ignore_control_dependency, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/true); std::vector<const HloInstruction*> nearest_common_ancestor( {forward_slice_output.nearest_common_ancestor_root()}); CHECK_EQ(nearest_common_ancestor.size(), 1); // Backward slicing from the nearest common ancestor to filter out // the redundant computations/instructions in the sliced result in step 1. SliceOutput backward_slice_output = SliceModuleHelper(hlo_module, /*slice_starting_instructions=*/ absl::MakeSpan(nearest_common_ancestor), /*frontier_selector=*/nullptr, ignore_control_dependency, /*forward_slice=*/false, /*nearest_common_ancestor_as_root=*/false); // Intersect the sliced instructions between forward slicing pass and // backward slicing pass as the new sliced instructions, and return the // new SliceOutput. return SliceOutput{SliceOutput::IntersectSlicedInstructions( forward_slice_output, backward_slice_output), backward_slice_output.frontier_instructions(), forward_slice_output.nearest_common_ancestor_root()}; } } else { // Backward slicing. return SliceModuleHelper(hlo_module, slice_starting_instructions, frontier_selector, ignore_control_dependency, /*forward_slice=*/false, /*nearest_common_ancestor_as_root=*/false); } } std::vector<std::unique_ptr<HloModule>> SliceModuleAndExtract( const HloModule* hlo_module, absl::Span<const HloInstruction*> slice_starting_instructions, const SlicingConfiguration& slicing_configuration) { std::vector<std::unique_ptr<HloModule>> sliced_modules; // Group `slice_starting_instructions` based on `slicing_group` configuration. int slicing_group = slicing_configuration.slicing_group; CHECK(slicing_group >= 1 || slicing_group == -1); std::vector<absl::Span<const HloInstruction*>> grouped_instructions; if (slicing_group == -1) { grouped_instructions = {slice_starting_instructions}; } else { for (int i = 0; i < slice_starting_instructions.size(); i += slicing_group) { // subspan can correctly handel the last group, which may be smaller than // `slicing_group`. grouped_instructions.push_back( slice_starting_instructions.subspan(i, slicing_group)); } } for (const auto& grouped_slice_starting_instructions : grouped_instructions) { // Forward slicing. SliceOutput forward_slice_output; if (slicing_configuration.forward_slicing == SlicingConfiguration::ForwardSlicingConfig::kRoot) { // Slice to the root instruction of the entry computation of `hlo_module`. forward_slice_output = SliceModule( hlo_module, grouped_slice_starting_instructions, /*frontier_selector=*/nullptr, /*ignore_control_dependency=*/false, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/false); } else if (slicing_configuration.forward_slicing == SlicingConfiguration::ForwardSlicingConfig::kNca) { // slice to the nearest common ancestors of // `grouped_slice_starting_instructions` forward_slice_output = SliceModule( hlo_module, grouped_slice_starting_instructions, /*frontier_selector=*/nullptr, /*ignore_control_dependency=*/false, /*forward_slice=*/true, /*nearest_common_ancestor_as_root=*/true); } VLOG(1) << "[Num of forward sliced insts]: " << forward_slice_output.NumSlicedInstructions(); // Backward slicing. SliceOutput backward_slice_output; if (slicing_configuration.backward_slicing) { backward_slice_output = SliceModule( hlo_module, grouped_slice_starting_instructions, /*frontier_selector=*/nullptr, /*ignore_control_dependency=*/false, /*forward_slice=*/false); } else { // Return the empty SliceOutput if backward slicing is not enabled. backward_slice_output = SliceOutput(); } // Combine forward slicing output and backward slicing output. auto sliced_result = SliceOutput(SliceOutput::UnionSlicedInstructions( forward_slice_output, backward_slice_output)); // Decide Root to start extraction based on `forward_slicing_config`. const HloInstruction* extraction_root = slicing_configuration.forward_slicing == SlicingConfiguration::ForwardSlicingConfig::kNca ? forward_slice_output.nearest_common_ancestor_root() : hlo_module->entry_computation()->root_instruction(); VLOG(1) << "[Root instruction of the sliced module]: " << extraction_root->ToString(); // Exclude the instructions that are not in the slicing results. auto extract_selector = [&sliced_result](const HloInstruction* hlo_inst) { for (const auto& [computation, instructions] : sliced_result.sliced_instructions()) { if (instructions.contains(hlo_inst)) { return true; } } return false; }; // Replace the excluded instructions in the entry computation with zeros. auto replace_type_selector = [](const HloInstruction* hlo_inst) -> ReplaceType { return ReplaceType::kReplaceZeroBroadcast; }; // Extract from the original module. auto extracted_module = ExtractModule(/*instruction=*/extraction_root, /*height=*/-1, /*extract_selector=*/extract_selector, /*replace_type_selector=*/replace_type_selector, /*cross_computation=*/true); // Remove the custom-call to sharding if `remove_sharding` is specified. if (slicing_configuration.remove_sharding) { RemoveSharding(extracted_module.get()); } // Reduce the parameter instructions of tuple shape if // `reduce_tuple_parameter` is specified. if (slicing_configuration.reduce_tuple_parameter) { ReduceTupleParameter(extracted_module.get()); } // Verify if the extracted module (after processing) is valid or not. HloVerifier verifier(/*layout_sensitive=*/false, /*allow_mixed_precision=*/true); TF_CHECK_OK(verifier.Run(extracted_module.get()).status()); sliced_modules.emplace_back(std::move(extracted_module)); } // Return all the sliced modules. CHECK_EQ(sliced_modules.size(), grouped_instructions.size()); return sliced_modules; } VLOG(1) << "[Num of forward sliced insts]: " VLOG(1) << "[Root instruction of the sliced module]: " auto extract_selector = [&sliced_result](const HloInstruction* hlo_inst) { for (const auto& [computation, instructions] : sliced_result.sliced_instructions()) { if (instructions.contains(hlo_inst)) { return true; } } return false; };
#include "xla/tools/hlo_slicer.h" #include <memory> #include <string> #include <utility> #include <vector> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/log/check.h" #include "absl/types/span.h" #include "xla/hlo/ir/hlo_computation.h" #include "xla/hlo/ir/hlo_instruction.h" #include "xla/hlo/ir/hlo_opcode.h" #include "xla/hlo/utils/hlo_matchers.h" #include "xla/tests/hlo_test_base.h" #include "tsl/platform/statusor.h" TEST_F(HloSlicerTest, TestSliceModuleAndExtractSlicingGroup) { const std::string& hlo_string = R"( HloModule axpy_module ENTRY axpy_computation (p.0: (s32[], s32[3]{0}), p.1: (s32[3]{0}, s32[])) -> s32[] { p.0 = (s32[], s32[3]{0}) parameter(0) gte.0 = s32[] get-tuple-element(p.0), index=0 p.1 = (s32[3]{0}, s32[]) parameter(1) gte.1 = s32[] get-tuple-element(p.1), index=1 ROOT add.0 = s32[] add(gte.0, gte.1) } )"; TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> hlo_module, ParseAndReturnVerifiedModule(hlo_string)); HloInstruction* gte_0 = FindInstruction(hlo_module.get(), "gte.0"); CHECK_NE(gte_0, nullptr); HloInstruction* gte_1 = FindInstruction(hlo_module.get(), "gte.1"); CHECK_NE(gte_1, nullptr); // slice_starting_instructions: {gte.0, gte.1}. // forward_slicing: kNca. // backward_slicing: true. // remove_sharding: false. // reduce_tuple_parameter: false. // slicing_group: 1 { // Generate two sliced modules, sliced from gte.0 and gte.1, respectively // (`slicing_group` = 1). std::vector<const HloInstruction*> relevant_instructions({gte_0, gte_1}); SlicingConfiguration slicing_config = { /*forward_slicing=*/SlicingConfiguration::ForwardSlicingConfig::kNca, /*backward_slicing=*/true, /*remove_sharding=*/false, /*reduce_tuple_parameter=*/false, /*slicing_group=*/1}; std::vector<std::unique_ptr<HloModule>> sliced_modules = SliceModuleAndExtract(hlo_module.get(), /*slice_starting_instructions=*/ absl::MakeSpan(relevant_instructions), /*slicing_configuration=*/slicing_config); // There are two sliced module. EXPECT_EQ(sliced_modules.size(), 2); // The first sliced module contains gte.0 and p.0. auto sliced_module_0 = std::move(sliced_modules[0]); EXPECT_EQ(sliced_module_0->entry_computation()->instruction_count(), 2); HloInstruction* p_0 = FindInstruction(sliced_module_0.get(), "p.0"); EXPECT_NE(p_0, nullptr); // The second sliced module contains gte.1 and p.1. auto sliced_module_1 = std::move(sliced_modules[1]); EXPECT_EQ(sliced_module_0->entry_computation()->instruction_count(), 2); HloInstruction* p_1 = FindInstruction(sliced_module_1.get(), "p.1"); EXPECT_NE(p_1, nullptr); } }
LiteralUtilTest_BitcastConvert
xla/literal_test.cc
bool LiteralProtoHasValues(const LiteralProto& proto) { return !proto.s2s().empty() || !proto.s4s().empty() || !proto.s8s().empty() || !proto.s16s().empty() || proto.s32s_size() || proto.s64s_size() || !proto.u2s().empty() || !proto.u4s().empty() || !proto.u8s().empty() || !proto.u16s().empty() || proto.u32s_size() || proto.u64s_size() || !proto.f8e5m2s().empty() || !proto.f8e4m3fns().empty() || !proto.f8e4m3b11fnuzs().empty() || !proto.f8e5m2fnuzs().empty() || !proto.f8e4m3fnuzs().empty() || !proto.f16s().empty() || !proto.bf16s().empty() || proto.f32s_size() || proto.f64s_size() || proto.c64s_size() || proto.c128s_size() || proto.preds_size() || proto.tuple_literals_size(); } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { const Shape& NilShape() { static const Shape* shape = new Shape(TUPLE, {}, {}, {}); return *shape; } const Shape* TryInternShape(const Shape& shape) { if (shape.IsTuple() && shape.tuple_shapes_size() == 0) { return &NilShape(); } if (shape.IsArray() && shape.dimensions_size() == 0 && shape.is_static() && shape.layout().tiles_size() == 0 && shape.layout().memory_space() == 0) { return &ScalarShape(shape.element_type()); } return nullptr; } StrideConfig::StrideConfig(const Shape& source_shape, const Shape& dest_shape, absl::Span<const int64_t> dimensions) : dimensions(dimensions), base(dimensions.size(), 0), step(dimensions.size(), 1) { if (!dimensions.empty()) { // Selects the shape with the largest minor dimension as the one upon // which to run the tight stride loop. if (dimensions[LayoutUtil::Minor(source_shape.layout(), 0)] >= dimensions[LayoutUtil::Minor(dest_shape.layout(), 0)]) { minor_dimension = LayoutUtil::Minor(source_shape.layout(), 0); dest_stride = IndexUtil::GetDimensionStride(dest_shape, minor_dimension); } else { minor_dimension = LayoutUtil::Minor(dest_shape.layout(), 0); source_stride = IndexUtil::GetDimensionStride(source_shape, minor_dimension); } minor_loop_size = dimensions[minor_dimension]; step[minor_dimension] = minor_loop_size; } } LiteralBase::~LiteralBase() = default; const Shape& LiteralBase::shape() const { return root_piece().subshape(); } const char* LiteralBase::Piece::buffer() const { // std::visit is avoided here due to its code size issues. if (auto* r = std::get_if<DenseRep>(&rep_)) { return r->data; } if (auto* r = std::get_if<DenseInlinedRep>(&rep_)) { return r->data; } DCHECK(std::holds_alternative<TupleRep>(rep_) || std::holds_alternative<Uninitialized>(rep_)); return nullptr; } const LiteralBase::Piece& LiteralBase::piece( const ShapeIndex& shape_index) const { const Piece* piece = &root_piece(); for (const auto i : shape_index) { DCHECK_GE(i, 0); DCHECK_LT(i, piece->children_size()); piece = &piece->child(i); } return *piece; } std::ostream& operator<<(std::ostream& out, const Literal& literal) { out << literal.ToString(); return out; } Shape* MutableLiteralBase::mutable_shape_do_not_use() { const Shape* const_shape = shape_.get(); if (!shape_.OwnsPtr()) { shape_ = MaybeOwningShapePtr(std::make_unique<Shape>(*shape_)); } Shape* shape = shape_.get_mutable(); if (shape != const_shape) { std::function<void(const Shape&, Piece*)> set_piece_shapes = [&set_piece_shapes](const Shape& shape, Piece* piece) { piece->set_subshape(&shape); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); set_piece_shapes(subshape, &piece->child(i)); } } }; set_piece_shapes(*shape, &mutable_root_piece()); } return shape; } [&set_piece_shapes](const Shape& shape, Piece* piece) { piece->set_subshape(&shape); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); set_piece_shapes(subshape, &piece->child(i)); } } }; Literal::Literal() : Literal(NilShape()) {} Literal::Literal(const Shape& shape) : Literal(shape, /*allocate_arrays=*/true) {} void Literal::SetShape(const Shape& shape) { Shape shape_storage; const Shape* shape_ptr = &shape; if (LayoutUtil::HasCustomElementSizeInBits(shape)) { shape_storage = shape; shape_storage.mutable_layout()->set_element_size_in_bits(0); shape_ptr = &shape_storage; } if (const Shape* intered_shape_ptr = TryInternShape(*shape_ptr)) { shape_ = intered_shape_ptr; } else { shape_ = std::make_unique<Shape>(*shape_ptr); } } void Literal::SetPiece(const Shape& shape, Piece* piece, bool allocate_arrays, ArrayValueState leaf_array_value_state) { if (shape.IsTuple()) { for (const Shape& subshape : shape.tuple_shapes()) { Piece child_piece; child_piece.set_subshape(&subshape); SetPiece(subshape, &child_piece, allocate_arrays, leaf_array_value_state); piece->emplace_back(std::move(child_piece)); } } else if (shape.IsArray()) { DCHECK(LayoutUtil::IsDenseArray(shape)) << "literal array storage is currently only supported for dense " "arrays: " << shape; piece->set_array_value_state(leaf_array_value_state); if (leaf_array_value_state == LiteralBase::ArrayValueState::kKnown && allocate_arrays) { piece->AllocateBuffers(); } } } Literal::Literal(const Shape& shape, bool allocate_arrays, ArrayValueState leaf_array_value_state) : MutableLiteralBase() { SetShape(shape); CHECK(leaf_array_value_state != ArrayValueState::kKnown || LayoutUtil::HasLayout(*shape_)); root_piece_.set_subshape(shape_.get()); CHECK(&root_piece_.subshape() == shape_.get()); SetPiece(*shape_, &root_piece_, allocate_arrays, leaf_array_value_state); } Literal::~Literal() { DeallocateBuffers(); } void Literal::DeallocateBuffers() { root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { piece->DeallocateBuffers(); }); } Literal::Literal(Literal&& other) : MutableLiteralBase() { *this = std::move(other); } Literal& Literal::operator=(Literal&& other) { DCHECK(&other.root_piece_.subshape() == other.shape_.get()); using std::swap; swap(shape_, other.shape_); swap(root_piece_, other.root_piece_); DCHECK(&root_piece_.subshape() == shape_.get()); return *this; } Literal LiteralBase::CreateFromShape(const Shape& shape) { Literal literal(shape); literal.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (piece->subshape().IsArray()) { memset(piece->untyped_data(), 0, piece->size_bytes_dense()); } }); return literal; } [&](const ShapeIndex& index, Piece* piece) { if (piece->subshape().IsArray()) { memset(piece->untyped_data(), 0, piece->size_bytes_dense()); } }); Literal LiteralBase::CreateFromShapeWithUnknownLeafArrays(const Shape& shape) { Literal literal(shape, /*allocate_arrays=*/false, ArrayValueState::kUnknown); return literal; } Literal LiteralBase::CreateFromShapeWithUndeterminedLeafArrays( const Shape& shape) { Literal literal(shape, /*allocate_arrays=*/false, ArrayValueState::kUndetermined); return literal; } int32_t LiteralBase::GetDynamicSize(int64_t dim_index) const { return GetDynamicSize(dim_index, {}); } int32_t LiteralBase::GetDynamicSize(int64_t dim_index, const ShapeIndex& shape_index) const { return piece(shape_index).GetDynamicSize(dim_index); } std::optional<int64_t> LiteralBase::GetFirstInteger() const { if (!primitive_util::IsIntegralType(shape().element_type())) { return std::nullopt; } return primitive_util::IntegralTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, void LiteralBase::BuildPieceSubtree(const Shape& shape, Piece* piece) { CHECK(shape.IsTuple()); for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); Piece child_piece; child_piece.set_subshape(&subshape); if (subshape.IsTuple()) { BuildPieceSubtree(subshape, &child_piece); } piece->emplace_back(std::move(child_piece)); } } absl::Status LiteralBase::SerializeToString(std::string* output) const { ShapeProto shape_proto = shape().ToProto(); TF_ASSIGN_OR_RETURN(int64_t size, ShapeUtil::SerializedSizeWithProto(shape(), shape_proto)); output->resize(size); return SerializeWithShapeProto(shape_proto, output->data()); } absl::StatusOr<std::string> LiteralBase::SerializeAsString() const { std::string result; TF_RETURN_IF_ERROR(SerializeToString(&result)); return std::move(result); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { void MutableLiteralBase::CopyElementFrom(const LiteralSlice& src_literal, absl::Span<const int64_t> src_index, absl::Span<const int64_t> dest_index) { DCHECK(LayoutUtil::IsDenseArray(shape())); DCHECK_EQ(shape().element_type(), src_literal.shape().element_type()); const int64_t src_linear_index = IndexUtil::MultidimensionalIndexToLinearIndex(src_literal.shape(), src_index); const int64_t dest_linear_index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), dest_index); const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); char* dest_address = static_cast<char*>(untyped_data()) + dest_linear_index * primitive_size; const char* source_address = static_cast<const char*>(src_literal.untyped_data()) + src_linear_index * primitive_size; if (dest_address != source_address) { memcpy(dest_address, source_address, primitive_size); } } /* static */ absl::StatusOr<Literal> MutableLiteralBase::CreateFromProto( const LiteralProto& proto, bool prohibit_empty_literal) { if (!proto.has_shape()) { return InvalidArgument("LiteralProto has no shape"); } Shape shape(proto.shape()); if (ShapeUtil::HasPrimitiveType(shape, OPAQUE_TYPE)) { return InvalidArgument( "Literal shape cannot include OPAQUE_TYPE sub-shape"); } if (!LayoutUtil::HasLayout(shape)) { return InvalidArgument("LiteralProto has no layout"); } if (LayoutUtil::IsSparseArray(shape)) { return Unimplemented("Sparse literals are not supported"); } TF_RETURN_IF_ERROR(ShapeUtil::ValidateShapeWithOptionalLayout(shape)); Literal literal(shape); TF_RETURN_IF_ERROR(literal.root_piece_.ForEachMutableSubpieceWithStatus( [&](const ShapeIndex& index, Piece* piece) -> absl::Status { const LiteralProto* proto_element = &proto; for (int64_t i : index) { CHECK(i < proto_element->tuple_literals_size()); proto_element = &proto_element->tuple_literals(i); } if (piece->subshape().IsTuple()) { if (proto_element->tuple_literals_size() != ShapeUtil::TupleElementCount(piece->subshape())) { return InvalidArgument( "Expected %d tuple elements in LiteralProto, has %d", ShapeUtil::TupleElementCount(piece->subshape()), proto_element->tuple_literals_size()); } return absl::OkStatus(); } if (piece->subshape().element_type() == TOKEN) { return absl::OkStatus(); } CHECK(piece->subshape().IsArray()); // When prohibit_empty_literal is false (allowing literal with no // values), only copy from proto if the literal proto has values. This // mode is used for a learned cost model. if (prohibit_empty_literal || LiteralProtoHasValues(*proto_element)) { TF_RETURN_IF_ERROR(piece->CopyFromProto(*proto_element)); } return absl::OkStatus(); })); return std::move(literal); } TF_RETURN_IF_ERROR(literal.root_piece_.ForEachMutableSubpieceWithStatus( Literal Literal::SubLiteral(ShapeIndexView shape_index) { if (!shape_index.empty()) { auto decomposed = this->DecomposeTuple(); return decomposed.at(shape_index.front()) .SubLiteral(shape_index.subspan(1)); } else { return std::move(*this); } } std::vector<Literal> Literal::DecomposeTuple() { CHECK(shape().IsTuple()); std::vector<Literal> elements; const auto tuple_element_count = ShapeUtil::TupleElementCount(shape()); elements.reserve(tuple_element_count); for (int i = 0; i < tuple_element_count; ++i) { elements.push_back(Literal(ShapeUtil::GetSubshape(shape(), {i}), /*allocate_arrays=*/false)); Literal& element = elements.back(); element.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* dest_piece) { if (dest_piece->subshape().IsTuple()) { return; } ShapeIndex src_index = {i}; for (int64_t j : index) { src_index.push_back(j); } Piece& src_piece = piece(src_index); // Move the respective buffer over to the element Literal. dest_piece->MoveDataFrom(src_piece); }); } // Set this literal to be nil-shaped. *this = Literal(); return elements; } [&](const ShapeIndex& index, Piece* dest_piece) { if (dest_piece->subshape().IsTuple()) { return; } ShapeIndex src_index = {i}; for (int64_t j : index) { src_index.push_back(j); } Piece& src_piece = piece(src_index); // Move the respective buffer over to the element Literal. dest_piece->MoveDataFrom(src_piece); }); void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } int32_t LiteralBase::Piece::GetDynamicSize(int64_t dim_index) const { CHECK(LayoutUtil::IsDenseArray(subshape())); if (!subshape_->is_dynamic_dimension(dim_index)) { // This is a static dimension, return size. return subshape_->dimensions(dim_index); } return dynamic_size_buffer()[dim_index]; } void LiteralBase::Piece::SetDynamicSize(int64_t dim_index, int32_t size) { CHECK(LayoutUtil::IsDenseArray(subshape())); CHECK(subshape_->is_dynamic_dimension(dim_index)); dynamic_size_buffer()[dim_index] = size; } void LiteralBase::Piece::AllocateBuffers() { const int64_t bytes = total_bytes_dense(); if (bytes > kMaxInlinedBytes) { CHECK_EQ(buffer(), nullptr); rep_.emplace<DenseRep>(); set_buffer( static_cast<char*>(tsl::port::AlignedMalloc(bytes, kMinimumAlignment))); } else { rep_.emplace<DenseInlinedRep>(); } } void LiteralBase::Piece::DeallocateBuffers() { if (auto* array_rep = GetDenseRep()) { tsl::port::AlignedFree(array_rep->data); rep_.emplace<Uninitialized>(); } } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } absl::Status LiteralBase::Piece::CopyFrom(const LiteralBase::Piece& src, bool only_dynamic_bound) { CHECK(subshape_ != nullptr); CHECK(src.subshape_ != nullptr); CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK(LayoutUtil::IsDenseArray(src.subshape())) << __func__ << " is only supported for dense arrays: " << src.subshape(); if (!only_dynamic_bound) { CHECK(ShapeUtil::Compatible(subshape(), src.subshape())); } if (src.array_value_state_ == ArrayValueState::kUnknown || src.array_value_state_ == ArrayValueState::kUndetermined) { if (array_value_state_ == ArrayValueState::kKnown) { DeallocateBuffers(); } array_value_state_ = src.array_value_state_; return absl::OkStatus(); } else { CHECK(src.array_value_state_ == ArrayValueState::kKnown); if (array_value_state_ == ArrayValueState::kUndetermined || array_value_state_ == ArrayValueState::kUnknown) { AllocateBuffers(); } array_value_state_ = src.array_value_state_; } if (ShapeUtil::Equal(subshape(), src.subshape())) { // If the layouts are equal it's faster just to memcpy. memcpy(buffer(), src.buffer(), src.size_bytes_dense()); } else { std::vector<int64_t> origin(subshape().rank(), 0); primitive_util::ArrayTypeSwitch<void>( [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, subshape().element_type()); } DCHECK_EQ(dynamic_size_buffer_bytes(), src.dynamic_size_buffer_bytes()); if (subshape().is_dynamic() && src.subshape().is_dynamic()) { memcpy(dynamic_size_buffer(), src.dynamic_size_buffer(), src.dynamic_size_buffer_bytes()); } return absl::OkStatus(); } [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, void MutableLiteralBase::SetDynamicSize(int64_t dim_index, int32_t size) { return SetDynamicSize(dim_index, {}, size); } void MutableLiteralBase::SetDynamicSize(int64_t dim_index, const ShapeIndex& shape_index, int32_t size) { Shape* subshape = ShapeUtil::GetMutableSubshape(mutable_shape_do_not_use(), shape_index); CHECK(LayoutUtil::IsDenseArray(*subshape)) << __func__ << " is only supported for dense arrays: " << *subshape; CHECK_GE(subshape->dimensions(dim_index), size); subshape->set_dynamic_dimension(dim_index, true); CHECK_EQ(&piece(shape_index).subshape(), subshape); piece(shape_index).SetDynamicSize(dim_index, size); } absl::Status MutableLiteralBase::CopyFrom(const LiteralSlice& src_literal, const ShapeIndex& dest_shape_index, const ShapeIndex& src_shape_index, bool only_dynamic_bound) { const Shape& dest_subshape = ShapeUtil::GetSubshape(shape(), dest_shape_index); const Shape& src_subshape = ShapeUtil::GetSubshape(src_literal.shape(), src_shape_index); if (only_dynamic_bound) { auto& bound_shape = dest_subshape.is_static() ? src_subshape : dest_subshape; auto& compact_shape = dest_subshape.is_static() ? dest_subshape : src_subshape; CHECK(ShapeUtil::DynamicShapeIsCompatible(compact_shape, bound_shape)) << compact_shape.ToString() << " vs " << bound_shape.ToString(); } else { if (!ShapeUtil::Compatible(dest_subshape, src_subshape)) { return InvalidArgument( "Destination subshape incompatible with source subshape: %s vs %s", ShapeUtil::HumanString(dest_subshape), ShapeUtil::HumanString(src_subshape)); } } return mutable_root_piece().ForEachMutableSubpieceWithStatus( [&](const ShapeIndex& index, Piece* piece) { if (!piece->subshape().IsArray()) { return absl::OkStatus(); } // Determine if this index is in the part of this literal that we want // to copy over from src_literal. bool in_subtree_to_copy = true; for (int i = 0; i < dest_shape_index.size(); ++i) { if (index[i] != dest_shape_index[i]) { in_subtree_to_copy = false; break; } } if (!in_subtree_to_copy) { return absl::OkStatus(); } // Construct the index of the corresponding piece in the source literal. ShapeIndex src_piece_index = src_shape_index; for (int64_t i = dest_shape_index.size(), end = index.size(); i < end; ++i) { src_piece_index.push_back(index[i]); } TF_RETURN_IF_ERROR( piece->CopyFrom(src_literal.piece(src_piece_index), /*only_dynamic_bound=*/only_dynamic_bound)); return absl::OkStatus(); }); } [&](const ShapeIndex& index, Piece* piece) { if (!piece->subshape().IsArray()) { return absl::OkStatus(); } // Determine if this index is in the part of this literal that we want // to copy over from src_literal. bool in_subtree_to_copy = true; for (int i = 0; i < dest_shape_index.size(); ++i) { if (index[i] != dest_shape_index[i]) { in_subtree_to_copy = false; break; } } if (!in_subtree_to_copy) { return absl::OkStatus(); } // Construct the index of the corresponding piece in the source literal. ShapeIndex src_piece_index = src_shape_index; for (int64_t i = dest_shape_index.size(), end = index.size(); i < end; ++i) { src_piece_index.push_back(index[i]); } TF_RETURN_IF_ERROR( piece->CopyFrom(src_literal.piece(src_piece_index), /*only_dynamic_bound=*/only_dynamic_bound)); return absl::OkStatus(); }); absl::Status Literal::MoveFrom(Literal&& src_literal, const ShapeIndex& dest_shape_index) { const Shape& dest_subshape = ShapeUtil::GetSubshape(shape(), dest_shape_index); if (!ShapeUtil::Equal(dest_subshape, src_literal.shape())) { return InvalidArgument( "Destination subshape not equal to source shape: %s vs %s", ShapeUtil::HumanString(dest_subshape), ShapeUtil::HumanString(src_literal.shape())); } src_literal.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& src_index, Piece* src_piece) { if (!src_piece->subshape().IsArray()) { return; } ShapeIndex dest_index = dest_shape_index; for (int64_t i : src_index) { dest_index.push_back(i); } Piece& dest_piece = piece(dest_index); dest_piece.DeallocateBuffers(); dest_piece.MoveDataFrom(*src_piece); }); src_literal.shape_ = MaybeOwningShapePtr(&NilShape()); src_literal.root_piece_ = Piece(); src_literal.root_piece_.set_subshape(src_literal.shape_.get()); return absl::OkStatus(); } [&](const ShapeIndex& src_index, Piece* src_piece) { if (!src_piece->subshape().IsArray()) { return; } ShapeIndex dest_index = dest_shape_index; for (int64_t i : src_index) { dest_index.push_back(i); } Piece& dest_piece = piece(dest_index); dest_piece.DeallocateBuffers(); dest_piece.MoveDataFrom(*src_piece); }); absl::Status MutableLiteralBase::CopySliceFrom( const LiteralSlice& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << shape(); TF_RET_CHECK(LayoutUtil::IsDenseArray(src_literal.shape())) << src_literal.shape(); TF_RET_CHECK(ShapeUtil::SameElementType(src_literal.shape(), shape())); TF_RET_CHECK(src_literal.shape().rank() == src_base.size()); TF_RET_CHECK(shape().rank() == dest_base.size()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, void MutableLiteralBase::PopulateR1(const tsl::core::Bitmap& values) { CHECK(shape().IsArray()); CHECK_EQ(shape().rank(), 1); CHECK_EQ(element_count(), values.bits()); CHECK_EQ(shape().element_type(), PRED); for (int64_t i = 0; i < static_cast<int64_t>(values.bits()); ++i) { Set({i}, values.get(i)); } } void MutableLiteralBase::PopulateInplaceInternal( absl::FunctionRef<void(void*, absl::Span<const int64_t>, int)> populator, bool parallel) { const Shape& this_shape = shape(); const int64_t rank = this_shape.rank(); DCHECK(LayoutUtil::IsDenseArray(this_shape)); char* const dest_base = static_cast<char*>(untyped_data()); if (rank > 0) { StrideConfig stride_config(this_shape, this_shape, this_shape.dimensions()); const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); const int64_t num_elements = ShapeUtil::ElementsIn(shape()); // If we are rank-1 and we are `parallel`, it is better to use a smaller // `step` than what `StrideConfig` does: stick the entire dimension in the // inner-most loop. if (parallel && this_shape.rank() == 1) { const int64_t thread_count = ShapeUtil::GetForEachIndexParallelThreadCount(); // Let's just divide up the array into small amounts per thread. stride_config.dest_stride = stride_config.minor_loop_size = num_elements > 32 ? std::max<int64_t>(num_elements / thread_count, 1) : num_elements; stride_config.step = {stride_config.minor_loop_size}; } auto init_function = [&](absl::Span<const int64_t> indexes, int thread_id) -> absl::StatusOr<bool> { const int64_t index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), indexes); DimensionVector minor_scan_indexes(rank, 0); std::copy(indexes.begin(), indexes.end(), minor_scan_indexes.begin()); char* dest_ptr = dest_base + index * primitive_size; char* const dest_end = dest_base + // This handles the case where minor_loop_size does not evenly divide // the most minor dimension. std::min(index + stride_config.minor_loop_size, num_elements) * primitive_size; while (dest_ptr < dest_end) { populator(dest_ptr, minor_scan_indexes, thread_id); ++minor_scan_indexes[stride_config.minor_dimension]; dest_ptr += primitive_size; } return true; }; if (parallel) { ShapeUtil::ForEachIndexParallel(this_shape, stride_config.base, stride_config.dimensions, stride_config.step, init_function); } else { ShapeUtil::ForEachIndex( this_shape, stride_config.base, stride_config.dimensions, stride_config.step, [&init_function]( absl::Span<const int64_t> indexes) -> absl::StatusOr<bool> { auto result_ignored = init_function(indexes, /*thread_id=*/-1); return true; }); } } else { // For scalars. populator(dest_base, {}, /*thread_id=*/-1); } } auto init_function = [&](absl::Span<const int64_t> indexes, int thread_id) -> absl::StatusOr<bool> { const int64_t index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), indexes); DimensionVector minor_scan_indexes(rank, 0); std::copy(indexes.begin(), indexes.end(), minor_scan_indexes.begin()); char* dest_ptr = dest_base + index * primitive_size; char* const dest_end = dest_base + // This handles the case where minor_loop_size does not evenly divide // the most minor dimension. std::min(index + stride_config.minor_loop_size, num_elements) * primitive_size; while (dest_ptr < dest_end) { populator(dest_ptr, minor_scan_indexes, thread_id); ++minor_scan_indexes[stride_config.minor_dimension]; dest_ptr += primitive_size; } return true; }; [&init_function]( absl::Span<const int64_t> indexes) -> absl::StatusOr<bool> { auto result_ignored = init_function(indexes, /*thread_id=*/-1); return true; }); absl::Status MutableLiteralBase::PopulateInplace( absl::FunctionRef<void(void*, absl::Span<const int64_t>)> populator) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); PopulateInplaceInternal( [&](void* dest, absl::Span<const int64_t> indexes, int /*thread_id*/) { return populator(dest, indexes); }, /*parallel=*/false); return absl::OkStatus(); } absl::Status MutableLiteralBase::PopulateInplaceParallel( absl::FunctionRef<void(void*, absl::Span<const int64_t>, int)> populator) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); PopulateInplaceInternal(populator, /*parallel=*/element_count() > 32); return absl::OkStatus(); } Literal LiteralBase::Relayout(const Layout& new_layout, const ShapeIndex& shape_index) const { // Create new shape with 'new_layout' set at the given shape index. Shape new_shape = shape(); Shape* subshape = ShapeUtil::GetMutableSubshape(&new_shape, shape_index); TF_CHECK_OK(LayoutUtil::ValidateLayoutForShape(new_layout, *subshape)); *subshape->mutable_layout() = new_layout; // LINT.IfChange // s4 literals are stored in uint8_t/int8_t, therefore element_size_in_bits // must be removed. if (subshape->layout().element_size_in_bits() == 4) { subshape->mutable_layout()->set_element_size_in_bits(0); } // LINT.ThenChange(//tensorflow/compiler/xla/types.h) Literal result(new_shape); TF_CHECK_OK(result.CopyFrom(*this)); return result; } Literal LiteralBase::Relayout(const Shape& shape_with_layout) const { CHECK(ShapeUtil::Compatible(shape_with_layout, shape())) << "Given shape_with_layout " << ShapeUtil::HumanString(shape_with_layout) << " not compatible with literal shape " << ShapeUtil::HumanString(shape()); Literal result = CreateFromShape(shape_with_layout); ShapeUtil::ForEachSubshape( result.shape(), [this, &result](const Shape& subshape, const ShapeIndex& index) { if (subshape.IsArray()) { TF_CHECK_OK(result.CopyFrom(*this, /*dest_shape_index=*/index, /*src_shape_index=*/index)); } }); return result; } [this, &result](const Shape& subshape, const ShapeIndex& index) { if (subshape.IsArray()) { TF_CHECK_OK(result.CopyFrom(*this, /*dest_shape_index=*/index, /*src_shape_index=*/index)); } }); Literal LiteralBase::ToBoundedDynamic(const Shape& bounded_shape) const { CHECK(bounded_shape.is_dynamic()); Literal result(bounded_shape); ShapeUtil::ForEachSubshape( shape(), [&](const Shape& subshape, const ShapeIndex& index) { if (!subshape.IsArray()) { return; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (bounded_shape.is_dynamic_dimension(i)) { result.SetDynamicSize(i, subshape.dimensions(i)); } } }); TF_CHECK_OK(result.CopyFrom(*this, {}, {}, /*only_dynamic_bound=*/true)); return result; } shape(), [&](const Shape& subshape, const ShapeIndex& index) { if (!subshape.IsArray()) { return; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (bounded_shape.is_dynamic_dimension(i)) { result.SetDynamicSize(i, subshape.dimensions(i)); } } }); Literal LiteralBase::ToStatic() const { // Create new shape with 'new_layout' set at the given shape index. Shape new_shape = shape(); ShapeUtil::ForEachMutableSubshape( &new_shape, [this](Shape* subshape, const ShapeIndex& index) { if (!subshape->IsArray()) { return; } for (int64_t i = 0; i < subshape->rank(); ++i) { // GetDynamicSize has a 32-bit return type and may truncate static // dimensions, so make sure to skip. if (!subshape->is_dynamic_dimension(i)) continue; subshape->set_dynamic_dimension(i, false); subshape->set_dimensions(i, GetDynamicSize(i, index)); } }); Literal result(new_shape); TF_CHECK_OK(result.CopyFrom(*this, {}, {}, /*only_dynamic_bound=*/true)); return result; } &new_shape, [this](Shape* subshape, const ShapeIndex& index) { if (!subshape->IsArray()) { return; } for (int64_t i = 0; i < subshape->rank(); ++i) { // GetDynamicSize has a 32-bit return type and may truncate static // dimensions, so make sure to skip. if (!subshape->is_dynamic_dimension(i)) continue; subshape->set_dynamic_dimension(i, false); subshape->set_dimensions(i, GetDynamicSize(i, index)); } }); absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { absl::StatusOr<Literal> LiteralBase::Broadcast( const Shape& result_shape, absl::Span<const int64_t> dimensions) const { const LiteralBase& src = *this; const Shape& src_shape = shape(); if (!src_shape.IsArray()) { return InvalidArgument("Broadcast only supports arrays."); } const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(src_shape.element_type()); switch (primitive_size) { case 0: return BroadcastHelper<0>(src, src_shape, result_shape, dimensions); case 1: return BroadcastHelper<1>(src, src_shape, result_shape, dimensions); case 2: return BroadcastHelper<2>(src, src_shape, result_shape, dimensions); case 4: return BroadcastHelper<4>(src, src_shape, result_shape, dimensions); case 8: return BroadcastHelper<8>(src, src_shape, result_shape, dimensions); case 16: return BroadcastHelper<16>(src, src_shape, result_shape, dimensions); default: LOG(FATAL) << "Unhandled primitive size " << primitive_size; return InvalidArgument("Unhandled primitive size"); break; } } absl::StatusOr<Literal> LiteralBase::Reshape( absl::Span<const int64_t> dimensions) const { if (!LayoutUtil::IsDenseArray(shape())) { return InvalidArgument("Reshape is only supported for dense arrays."); } if (shape().is_dynamic()) { // TODO(b/243182930): We should consider supporting dynamic reshape. return Unimplemented("Dynamic reshape is not implemented."); } Literal output; if (!LayoutUtil::IsMonotonicWithDim0Major(shape().layout())) { output = Relayout(LayoutUtil::GetDefaultLayoutForRank(shape().rank())); } else { output = Clone(); } // Because the layout is monotonic, we can simply reuse the same sequence of // values without changing their order. *output.mutable_shape_do_not_use() = ShapeUtil::MakeShape(shape().element_type(), dimensions); int64_t elements_before = ShapeUtil::ElementsIn(shape()); int64_t elements_after = ShapeUtil::ElementsIn(output.shape()); if (elements_before != elements_after) { return InvalidArgument( "Shapes before and after Literal::Reshape have different numbers " "of elements: %s vs %s.", ShapeUtil::HumanString(shape()), ShapeUtil::HumanString(output.shape())); } return std::move(output); } Literal LiteralBase::Transpose(absl::Span<const int64_t> permutation) const { CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); CHECK(shape().rank() == permutation.size() && IsPermutation(permutation)) << "Given permutation is not a permutation of dimension numbers"; // To transpose the array, we just permute the dimensions and layout, and // do a straight memory copy of the raw data set. // This is considerably faster than iterating over every array element using // the EachCell<>() and Set<>() APIs. Shape permuted_shape = ShapeUtil::PermuteDimensions(permutation, shape()); // Replace the layout with one affine to this shape, such that a // transpose operation can be performed by leaving the flat values // representation intact. // For example, consider the shape F32[11,8]{1,0} under a {1,0} permutation. // The shape with affine layout resulting from that operation will be // F32[8,11]{0,1}, since it leaves the original most minor (the 8 sized), the // most minor. // // Essentially, given MinMaj(Di) the position of the Di dimension within the // minor to major vector, and given T(Di) the index that the original Di // dimension has within the transposed array, a layout is affine if // MinMaj(Di) == TMinMaj(T(Di)), with TMinMaj() being the minor to major // vector of the affine layout. std::vector<int64_t> inverse_permutation = InversePermutation(permutation); CHECK(LayoutUtil::IsDenseArray(permuted_shape)); Layout* layout = permuted_shape.mutable_layout(); layout->clear_minor_to_major(); for (auto index : LayoutUtil::MinorToMajor(shape())) { layout->add_minor_to_major(inverse_permutation[index]); } Literal new_literal(permuted_shape); if (shape().is_dynamic()) { for (int64_t i = 0; i < shape().rank(); i++) { if (shape().is_dynamic_dimension(i)) { // Set the dynamic size of any dynamic dimension in the transposed // literal. new_literal.SetDynamicSize(inverse_permutation[i], GetDynamicSize(i)); } } } DCHECK_EQ(ShapeUtil::ByteSizeOf(new_literal.shape()), ShapeUtil::ByteSizeOf(shape())); std::memcpy(new_literal.untyped_data(), untyped_data(), size_bytes()); return new_literal; } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( Literal LiteralBase::Slice(absl::Span<const int64_t> start_indices, absl::Span<const int64_t> limit_indices) const { CHECK(shape().IsArray()) << "tuple is not supported for slice"; DimensionVector result_dimensions; for (int64_t dnum = 0; dnum < shape().rank(); ++dnum) { CHECK_GE(start_indices[dnum], 0); CHECK_LE(limit_indices[dnum], shape().dimensions(dnum)) << "dnum = " << dnum; int64_t dimension = limit_indices[dnum] - start_indices[dnum]; CHECK_GE(dimension, 0) << "dnum = " << dnum; result_dimensions.push_back(dimension); } auto result_shape = ShapeUtil::MakeShapeWithDenseLayout( shape().element_type(), result_dimensions, LayoutUtil::MinorToMajor(shape())); ShapeUtil::CopyDynamicDimensions(&result_shape, shape()); Literal result_literal(result_shape); primitive_util::ArrayTypeSwitch<void>( [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; return SliceInternal<NativeT>(*this, start_indices, result_literal); }, result_shape.element_type()); return result_literal; } Literal LiteralBase::Clone() const { Literal result(shape()); TF_CHECK_OK(result.CopyFrom(*this)); return result; } std::unique_ptr<Literal> LiteralBase::CloneToUnique() const { auto result = std::make_unique<Literal>(shape()); TF_CHECK_OK(result->CopyFrom(*this)); return result; } bool LiteralBase::IsDetermined(const ShapeIndex& shape_index) const { return piece(shape_index).IsDetermined(); } bool LiteralBase::IsKnown(const ShapeIndex& shape_index) const { return piece(shape_index).IsKnown(); } std::string LiteralBase::GetAsString(absl::Span<const int64_t> multi_index, const ShapeIndex& shape_index) const { const Shape& subshape = ShapeUtil::GetSubshape(shape(), shape_index); CHECK(LayoutUtil::IsDenseArray(subshape)); return primitive_util::ArrayTypeSwitch<std::string>( [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, subshape.element_type()); } [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, std::optional<int64_t> LiteralBase::GetIntegralAsS64( absl::Span<const int64_t> multi_index) const { CHECK(LayoutUtil::IsDenseArray(shape())); return primitive_util::PrimitiveTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, std::optional<double> LiteralBase::GetAsDouble( absl::Span<const int64_t> multi_index) const { const Shape& s = shape(); CHECK(LayoutUtil::IsDenseArray(s)); return primitive_util::PrimitiveTypeSwitch<std::optional<double>>( [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, s.element_type()); } [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, std::optional<double> LiteralBase::GetSumAsDouble( absl::Span<const int64_t> linear_indices) const { const Shape& s = shape(); CHECK(LayoutUtil::IsDenseArray(s)); if (!primitive_util::IsFloatingPointType(s.element_type())) { return std::nullopt; } return primitive_util::FloatingPointTypeSwitch<double>( [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, s.element_type()); } [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, std::optional<complex128> LiteralBase::GetAsComplex128( absl::Span<const int64_t> multi_index) const { return primitive_util::PrimitiveTypeSwitch<std::optional<complex128>>( [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, absl::Status MutableLiteralBase::SetIntegralAsS64( absl::Span<const int64_t> multi_index, int64_t value) { CHECK(LayoutUtil::IsDenseArray(shape())); return primitive_util::PrimitiveTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, absl::Status MutableLiteralBase::SetFromDouble( absl::Span<const int64_t> multi_index, double value) { CHECK(LayoutUtil::IsDenseArray(shape())); if (!primitive_util::IsFloatingPointType(shape().element_type())) { return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); } primitive_util::FloatingPointTypeSwitch<void>( [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, shape().element_type()); return absl::OkStatus(); } [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, void PrintShape(bool print_layout, const Shape& shape, Printer* printer) { if (print_layout) { ShapeUtil::PrintHumanStringWithLayout(printer, shape); } else { ShapeUtil::PrintHumanString(printer, shape); } } void TuplePrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); printer->Append(oneline ? "( " : "(\n"); for (int i = 0; i < ShapeUtil::TupleElementCount(subshape); ++i) { ShapeIndex element_index = shape_index; element_index.push_back(i); if (i > 0) printer->Append(oneline ? ", " : ",\n"); PrintHelper(literal, element_index, print_shape, print_layout, oneline, printer); } printer->Append(oneline ? " )" : "\n)"); } void DenseArrayPrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); int64_t rank = subshape.rank(); const absl::string_view linebreak = oneline ? " " : "\n"; std::function<void(absl::Span<const int64_t> dimensions, std::vector<int64_t>*)> print_recursive = [&](absl::Span<const int64_t> dimensions, std::vector<int64_t>* accum_indices) { // dimensions.size() decreases by 1 at each recursive call, // and accum_indices->size() increases by 1. // Their sum is equal to the rank of the tensor. CHECK_EQ(rank, dimensions.size() + accum_indices->size()); auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; if (dimensions.empty()) { // Display predicates as 0s and 1s so that the string is more dense. std::string elem; if (subshape.element_type() == PRED && rank > 0) { elem = literal.Get<bool>(*accum_indices, shape_index) ? "1" : "0"; } else { elem = literal.GetAsString(*accum_indices, shape_index); } printer->Append(elem); } else { printer->Append(brace_to_string("{")); for (int i = 0; i < dimensions[0]; ++i) { accum_indices->push_back(i); print_recursive(dimensions.subspan(1), accum_indices); accum_indices->pop_back(); if (i < dimensions[0] - 1) { printer->Append(","); printer->Append(dimensions.size() > 1 ? linebreak : " "); } } printer->Append(brace_to_string("}")); } }; if (print_shape) { PrintShape(print_layout, subshape, printer); if (subshape.is_dynamic()) { printer->Append("("); for (int64_t i = 0; i < subshape.dimensions_size(); ++i) { printer->Append(literal.GetDynamicSize(i, shape_index)); if (i < subshape.dimensions_size() - 1) { printer->Append(","); } } printer->Append(")"); } printer->Append(" "); } std::vector<int64_t> indices = {}; std::vector<int64_t> dimensions; dimensions.reserve(subshape.rank()); for (int64_t i = 0; i < subshape.rank(); ++i) { dimensions.push_back(literal.GetDynamicSize(i, shape_index)); } print_recursive(dimensions, &indices); } print_recursive = [&](absl::Span<const int64_t> dimensions, std::vector<int64_t>* accum_indices) { // dimensions.size() decreases by 1 at each recursive call, // and accum_indices->size() increases by 1. // Their sum is equal to the rank of the tensor. CHECK_EQ(rank, dimensions.size() + accum_indices->size()); auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; if (dimensions.empty()) { // Display predicates as 0s and 1s so that the string is more dense. std::string elem; if (subshape.element_type() == PRED && rank > 0) { elem = literal.Get<bool>(*accum_indices, shape_index) ? "1" : "0"; } else { elem = literal.GetAsString(*accum_indices, shape_index); } printer->Append(elem); } else { printer->Append(brace_to_string("{")); for (int i = 0; i < dimensions[0]; ++i) { accum_indices->push_back(i); print_recursive(dimensions.subspan(1), accum_indices); accum_indices->pop_back(); if (i < dimensions[0] - 1) { printer->Append(","); printer->Append(dimensions.size() > 1 ? linebreak : " "); } } printer->Append(brace_to_string("}")); } }; auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; void PrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); CHECK(LayoutUtil::HasLayout(literal.shape())); CHECK(LayoutUtil::HasLayout(subshape)); if (subshape.IsTuple()) { TuplePrintHelper(literal, shape_index, print_shape, print_layout, oneline, printer); } else if (subshape.IsToken()) { printer->Append("token"); } else { CHECK(LayoutUtil::IsDenseArray(subshape)); if (literal.IsKnown(shape_index)) { DenseArrayPrintHelper(literal, shape_index, print_shape, print_layout, oneline, printer); } else { PrintShape(print_layout, subshape, printer); printer->Append(" "); if (literal.IsDetermined(shape_index)) { printer->Append("unknown"); } else { printer->Append("undetermined"); } } } } void LiteralBase::Print(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/false, /*oneline=*/false, printer); } void LiteralBase::PrintOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/false, /*oneline=*/true, printer); } void LiteralBase::PrintWithoutShape(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/false, /*print_layout=*/false, /*oneline=*/false, printer); } void LiteralBase::PrintWithoutShapeOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/false, /*print_layout=*/false, /*oneline=*/true, printer); } void LiteralBase::PrintWithLayout(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/true, /*oneline=*/false, printer); } void LiteralBase::PrintWithLayoutOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/true, /*oneline=*/true, printer); } std::string LiteralBase::ToString() const { StringPrinter printer; Print(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringOneline() const { StringPrinter printer; PrintOneline(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithoutShape() const { StringPrinter printer; PrintWithoutShape(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithoutShapeOneline() const { StringPrinter printer; PrintWithoutShapeOneline(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithLayout() const { StringPrinter printer; PrintWithLayout(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithLayoutOneline() const { StringPrinter printer; PrintWithLayoutOneline(&printer); return std::move(printer).ToString(); } void LiteralBase::EachCellAsString( absl::FunctionRef<void(absl::Span<const int64_t> indices, const std::string& value)> per_cell) const { if (ShapeUtil::IsZeroElementArray(shape())) { return; } auto indices = IndexUtil::LinearIndexToMultidimensionalIndex( shape(), /*linear_index=*/0); do { per_cell(indices, GetAsString(indices)); } while (IndexUtil::BumpIndices(shape(), absl::MakeSpan(indices))); } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { absl::StatusOr<Literal> ConvertSwitch(const LiteralBase& literal, PrimitiveType primitive_dest_type) { TF_RET_CHECK(LayoutUtil::IsDenseArray(literal.shape())); if (literal.shape().element_type() == primitive_dest_type) { return literal.Clone(); } // Source Array type requirement is ensured by IsDenseArray before. if (!primitive_util::IsArrayType(primitive_dest_type) || !primitive_util::IsArrayType(literal.shape().element_type())) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(literal.shape().element_type()), PrimitiveType_Name(primitive_dest_type)); } // At this point, we know both src & dst are array types, while src is not // complex type, so we can allocate the result literal here to avoid // duplicating it N^2 times in the conversion implementation. Literal result( ShapeUtil::ChangeElementType(literal.shape(), primitive_dest_type)); TF_RETURN_IF_ERROR(primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { return ConvertIfDestTypeMatches<primitive_type_constant>(literal, result); }, literal.shape().element_type())); return result; } absl::StatusOr<Literal> LiteralBase::Convert( PrimitiveType primitive_dest_type) const { return ConvertSwitch(*this, primitive_dest_type); } absl::StatusOr<Literal> LiteralBase::BitcastConvert( const Shape& dest_shape) const { if (ShapeUtil::ByteSizeOf(dest_shape) != ShapeUtil::ByteSizeOf(shape())) { return InvalidArgument( "Can not bitcast-convert from shape %s to a shape of different size %s", shape().ToString(), dest_shape.ToString()); } if (dest_shape.IsTuple() || shape().IsTuple()) { return InvalidArgument( "bitcast-convert is not valid for tuple shapes %s->%s", shape().ToString(), dest_shape.ToString()); } if (shape().is_dynamic() || dest_shape.is_dynamic()) { return InvalidArgument( "bitcast-convert is not valid for dynamic shape %s->%s", shape().ToString(), dest_shape.ToString()); } Literal out(dest_shape); std::memcpy(out.root_piece_.buffer(), root_piece().buffer(), root_piece().size_bytes_dense()); // Perform the reshape on little endian encoding even on big endian machines. if constexpr (!kLittleEndian) { // Swap byte ordering as per the input data type. size_t input_elem_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); TF_RETURN_IF_ERROR(tsl::ByteSwapArray( const_cast<char*>(out.root_piece().buffer()), input_elem_size, out.root_piece().size_bytes_dense() / input_elem_size)); // Swap byte ordering as per the output data type. size_t output_elem_size = ShapeUtil::ByteSizeOfPrimitiveType(dest_shape.element_type()); TF_RETURN_IF_ERROR(tsl::ByteSwapArray( const_cast<char*>(out.root_piece().buffer()), output_elem_size, out.root_piece().size_bytes_dense() / output_elem_size)); } return out; } absl::StatusOr<Literal> LiteralBase::ConvertToShape( const Shape& dest_shape) const { if (!dest_shape.IsTuple()) { return Convert(dest_shape.element_type()); } std::vector<Literal> elements; const auto tuple_element_count = ShapeUtil::TupleElementCount(shape()); elements.reserve(tuple_element_count); for (int i = 0; i < tuple_element_count; ++i) { auto element = LiteralSlice(*this, {i}); TF_ASSIGN_OR_RETURN( auto new_element, element.ConvertToShape(ShapeUtil::GetSubshape(dest_shape, {i}))); elements.push_back(std::move(new_element)); } return MutableLiteralBase::MoveIntoTuple(absl::MakeSpan(elements)); } /* static */ Literal MutableLiteralBase::MoveIntoTuple( absl::Span<Literal> elements) { std::vector<const Shape*> element_shapes; element_shapes.reserve(elements.size()); for (const Literal& element : elements) { element_shapes.push_back(&element.shape()); } Literal literal(ShapeUtil::MakeTupleShapeWithPtrs(element_shapes), /*allocate_arrays=*/false); for (int i = 0, end = elements.size(); i < end; ++i) { TF_CHECK_OK( literal.MoveFrom(std::move(elements[i]), /*dest_shape_index=*/{i})); } return literal; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualDynamicSize( const LiteralBase::Piece& other) const { DCHECK(ShapeUtil::Compatible(subshape(), other.subshape())); if (subshape().is_static()) { return true; } for (int64_t i = 0; i < subshape().rank(); ++i) { if (GetDynamicSize(i) != other.GetDynamicSize(i)) { return false; } } return true; } bool LiteralBase::Piece::EqualElements(const LiteralBase::Piece& other) const { if (subshape().is_static() && ShapeUtil::Equal(subshape(), other.subshape()) && subshape().IsArray()) { CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(size_bytes_dense(), other.size_bytes_dense()); if (primitive_util::IsSubByteNonPredType(subshape().element_type())) { CHECK(!primitive_util::IsFloatingPointType(subshape().element_type())); auto one_array = buffer(); auto two_array = other.buffer(); const int bits_per_element = primitive_util::BitWidth(subshape().element_type()); const uint8_t mask = LsbMask<uint8_t>(bits_per_element); for (int64_t i = 0; i < size_bytes_dense(); ++i) { if ((one_array[i] & mask) != (two_array[i] & mask)) return false; } return true; } return memcmp(buffer(), other.buffer(), size_bytes_dense()) == 0; } std::vector<int64_t> multi_index; return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeSrcT = NativeTypeOf<primitive_type_constant>; return EqualElementsInternal<NativeSrcT>(other, &multi_index); }, subshape().element_type()); } bool LiteralBase::Equal(const LiteralBase& other, bool layout_sensitive) const { // Checking the structure of tuple literals. Checks for dense arrays are // performed below. if (!ShapeUtil::EqualStructure(shape(), other.shape())) { return false; } return root_piece().ForEachSubpieceWithBool([&](const ShapeIndex& index, const Piece& piece) { const Piece& other_piece = other.piece(index); const Shape& subshape = piece.subshape(); const Shape& other_subshape = other_piece.subshape(); if (subshape.element_type() != other_subshape.element_type()) { return false; } if (!piece.subshape().IsArray()) { return true; } if (subshape.rank() != other_subshape.rank()) { return false; } if (layout_sensitive && (subshape.layout() != other_subshape.layout())) { return false; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (piece.GetDynamicSize(i) != other_piece.GetDynamicSize(i)) { return false; } } if (!piece.EqualElements(other_piece)) { return false; } return true; }); } return root_piece().ForEachSubpieceWithBool([&](const ShapeIndex& index, const Piece& piece) { const Piece& other_piece = other.piece(index); const Shape& subshape = piece.subshape(); const Shape& other_subshape = other_piece.subshape(); if (subshape.element_type() != other_subshape.element_type()) { return false; } if (!piece.subshape().IsArray()) { return true; } if (subshape.rank() != other_subshape.rank()) { return false; } if (layout_sensitive && (subshape.layout() != other_subshape.layout())) { return false; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (piece.GetDynamicSize(i) != other_piece.GetDynamicSize(i)) { return false; } } if (!piece.EqualElements(other_piece)) { return false; } return true; }); static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(std::complex<T> a, std::complex<T> b) { return EqualIncludingNan(a.real(), b.real()) && EqualIncludingNan(a.imag(), b.imag()); } static bool EqualIncludingNan(std::complex<T> a, std::complex<T> b) { return EqualIncludingNan(a.real(), b.real()) && EqualIncludingNan(a.imag(), b.imag()); } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } bool Literal::Piece::IsAll(const Literal& scalar) const { CHECK(ShapeUtil::IsScalar(scalar.shape())) << scalar.shape().ToString(); if (!subshape().IsArray()) { return false; } CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(subshape().element_type(), scalar.shape().element_type()); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, subshape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, int64_t Literal::Piece::CountAll(const Literal& scalar) const { CHECK(ShapeUtil::IsScalar(scalar.shape())) << scalar.shape().ToString(); if (!subshape().IsArray()) { return 0; } CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(subshape().element_type(), scalar.shape().element_type()); return primitive_util::ArrayTypeSwitch<int64_t>( [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, subshape().element_type()); } [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { bool LiteralBase::IsAll(const Literal& scalar) const { return root_piece().IsAll(scalar); } bool LiteralBase::IsAll(int8_t value) const { if (!shape().IsArray()) { return false; } PrimitiveType ty = shape().element_type(); if (primitive_util::IsFloatingPointType(ty)) { return IsAllFloatImpl(value, /*round_value=*/false); } if (primitive_util::IsUnsignedIntegralType(ty) && value < 0) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllFloat(float value) const { return IsAllFloatImpl(value, /*round_value=*/true); } bool LiteralBase::IsAllFloatImpl(float value, bool round_value) const { PrimitiveType ty = shape().element_type(); if (!primitive_util::IsFloatingPointType(ty)) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::FloatingPointTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllComplex(complex64 value) const { PrimitiveType ty = shape().element_type(); if (!primitive_util::IsComplexType(ty)) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::ComplexTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllFirst() const { if (!shape().IsArray()) { return false; } // Empty shapes are not all the first element since there is no first element. if (ShapeUtil::IsZeroElementArray(shape())) { return false; } absl::InlinedVector<int64_t, 4> start_indices(/*n=*/shape().rank(), 0); absl::InlinedVector<int64_t, 4> end_indices(/*n=*/shape().rank(), 1); Literal first = Slice(start_indices, end_indices); return IsAll(first.Reshape({}).value()); } bool LiteralBase::IsR1Iota() const { if (!shape().IsArray()) { return false; } CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); if (shape().rank() != 1) { return false; } return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, shape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, std::optional<int64_t> LiteralBase::IsR1StridedIota() const { if (!shape().IsArray() || shape().rank() != 1) { return std::nullopt; } CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); const int64_t elements = ShapeUtil::ElementsIn(shape()); const PrimitiveType type = shape().element_type(); if (elements <= 1 || !primitive_util::IsIntegralType(type)) { return std::nullopt; } return primitive_util::IntegralTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, bool LiteralBase::IsZero(absl::Span<const int64_t> indices) const { CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, shape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void LiteralBase::Piece::set_array_value_state(ArrayValueState state) { array_value_state_ = state; } LiteralBase::ArrayValueState LiteralBase::Piece::get_array_value_state() const { return array_value_state_; } void LiteralBase::Piece::WriteToProto(LiteralProto* proto) const { *proto->mutable_shape() = subshape().ToProto(); switch (subshape().element_type()) { case PRED: CopyToRepeatedField(proto->mutable_preds(), data<bool>()); break; case U2: *proto->mutable_u2s() = std::string( reinterpret_cast<const char*>(data<u2>().data()), size_bytes_dense()); break; case U4: *proto->mutable_u4s() = std::string( reinterpret_cast<const char*>(data<u4>().data()), size_bytes_dense()); break; case U8: proto->set_u8s(static_cast<const unsigned char*>(data<uint8_t>().data()), element_count()); break; case U16: *proto->mutable_u16s() = std::string(reinterpret_cast<const char*>(data<uint16_t>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_u16s()); } break; case U32: CopyToRepeatedField(proto->mutable_u32s(), data<uint32_t>()); break; case U64: CopyToRepeatedField(proto->mutable_u64s(), data<uint64_t>()); break; case S2: *proto->mutable_s2s() = std::string( reinterpret_cast<const char*>(data<s2>().data()), size_bytes_dense()); break; case S4: *proto->mutable_s4s() = std::string( reinterpret_cast<const char*>(data<s4>().data()), size_bytes_dense()); break; case S8: proto->set_s8s(static_cast<const signed char*>(data<int8_t>().data()), element_count()); break; case S16: *proto->mutable_s16s() = std::string(reinterpret_cast<const char*>(data<int16_t>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_s16s()); } break; case S32: CopyToRepeatedField(proto->mutable_s32s(), data<int32_t>()); break; case S64: CopyToRepeatedField(proto->mutable_s64s(), data<int64_t>()); break; case F8E5M2: *proto->mutable_f8e5m2s() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e5m2>().data()), size_bytes_dense()); break; case F8E4M3FN: *proto->mutable_f8e4m3fns() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3fn>().data()), size_bytes_dense()); break; case F8E4M3B11FNUZ: *proto->mutable_f8e4m3b11fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3b11fnuz>().data()), size_bytes_dense()); break; case F8E5M2FNUZ: *proto->mutable_f8e5m2fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e5m2fnuz>().data()), size_bytes_dense()); break; case F8E4M3FNUZ: *proto->mutable_f8e4m3fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3fnuz>().data()), size_bytes_dense()); break; case F16: *proto->mutable_f16s() = std::string(reinterpret_cast<const char*>(data<half>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_f16s()); } break; case BF16: *proto->mutable_bf16s() = std::string(reinterpret_cast<const char*>(data<bfloat16>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_bf16s()); } break; case F32: CopyToRepeatedField(proto->mutable_f32s(), data<float>()); break; case F64: CopyToRepeatedField(proto->mutable_f64s(), data<double>()); break; case C64: for (complex64 value : data<complex64>()) { proto->add_c64s(value.real()); proto->add_c64s(value.imag()); } break; case C128: for (complex128 value : data<complex128>()) { proto->add_c128s(value.real()); proto->add_c128s(value.imag()); } break; case TUPLE: case TOKEN: // Nothing to do but assign the shape which is done above. return; default: // TODO(b/111551621): Support serializing more PrimitiveTypes. LOG(FATAL) << "Unhandled primitive type " << PrimitiveType_Name(subshape().element_type()); } } const void* LiteralBase::Piece::untyped_data() const { DCHECK(LayoutUtil::IsDenseArray(subshape())) << ShapeUtil::HumanString(subshape()); return buffer(); } void* LiteralBase::Piece::untyped_data() { DCHECK(LayoutUtil::IsDenseArray(subshape())) << ShapeUtil::HumanString(subshape()); return buffer(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status LiteralBase::Piece::CopyFromProto(const LiteralProto& proto) { // These conditions should have been checked in // MutableLiteralBase::CreateFromProto. TF_RET_CHECK(proto.has_shape()); Shape shape(proto.shape()); TF_RET_CHECK(LayoutUtil::HasLayout(shape)); TF_RET_CHECK(ShapeUtil::Equal(shape, subshape())); switch (subshape().element_type()) { case PRED: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<bool>(), proto.preds())); break; case S2: { const std::string& s(proto.s2s()); TF_RET_CHECK(data<s2>().size() * sizeof(s2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case S4: { const std::string& s(proto.s4s()); TF_RET_CHECK(data<s4>().size() * sizeof(s4) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case S8: { auto s8_data = data<int8_t>(); TF_RET_CHECK(proto.s8s().size() == s8_data.size()); std::copy(proto.s8s().begin(), proto.s8s().end(), s8_data.begin()); break; } case S16: { const std::string& s(proto.s16s()); TF_RET_CHECK(data<int16_t>().size() * sizeof(int16_t) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case S32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<int32_t>(), proto.s32s())); break; case S64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<int64_t>(), proto.s64s())); break; case U2: { const std::string& s(proto.u2s()); TF_RET_CHECK(data<u2>().size() * sizeof(u2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case U4: { const std::string& s(proto.u4s()); TF_RET_CHECK(data<u4>().size() * sizeof(u4) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case U8: { auto u8_data = data<uint8_t>(); TF_RET_CHECK(proto.u8s().size() == u8_data.size()); std::copy(proto.u8s().begin(), proto.u8s().end(), u8_data.begin()); break; } case U16: { const std::string& s(proto.u16s()); TF_RET_CHECK(data<uint16_t>().size() * sizeof(uint16_t) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case U32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<uint32_t>(), proto.u32s())); break; case U64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<uint64_t>(), proto.u64s())); break; case F8E5M2: { const std::string& s(proto.f8e5m2s()); TF_RET_CHECK(data<tsl::float8_e5m2>().size() * sizeof(tsl::float8_e5m2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3FN: { const std::string& s(proto.f8e4m3fns()); TF_RET_CHECK(data<tsl::float8_e4m3fn>().size() * sizeof(tsl::float8_e4m3fn) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3B11FNUZ: { const std::string& s(proto.f8e4m3b11fnuzs()); TF_RET_CHECK(data<tsl::float8_e4m3b11fnuz>().size() * sizeof(tsl::float8_e4m3b11fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E5M2FNUZ: { const std::string& s(proto.f8e5m2fnuzs()); TF_RET_CHECK(data<tsl::float8_e5m2fnuz>().size() * sizeof(tsl::float8_e5m2fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3FNUZ: { const std::string& s(proto.f8e4m3fnuzs()); TF_RET_CHECK(data<tsl::float8_e4m3fnuz>().size() * sizeof(tsl::float8_e4m3fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F16: { const std::string& s(proto.f16s()); TF_RET_CHECK(data<half>().size() * sizeof(half) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case BF16: { const std::string& s(proto.bf16s()); TF_RET_CHECK(data<bfloat16>().size() * sizeof(bfloat16) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case F32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<float>(), proto.f32s())); break; case F64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<double>(), proto.f64s())); break; case C64: { auto complex_data = data<complex64>(); TF_RET_CHECK(proto.c64s_size() == complex_data.size() * 2); for (int64_t i = 0; i < complex_data.size(); ++i) { complex_data[i] = complex64{proto.c64s(i * 2), proto.c64s(i * 2 + 1)}; } break; } case C128: { auto complex_data = data<complex128>(); const int64_t complex_data_size_doubled = complex_data.size() * 2; TF_RET_CHECK(proto.c128s_size() == complex_data_size_doubled); for (int64_t i = 0, end = complex_data.size(); i < end; ++i) { complex_data[i] = complex128{proto.c128s(i * 2), proto.c128s(i * 2 + 1)}; } break; } case TUPLE: return InvalidArgument("Should not be called on tuple shapes: %s", ShapeUtil::HumanString(subshape())); default: return InvalidArgument("Is called on unsupported shape: %s", ShapeUtil::HumanString(subshape())); } return absl::OkStatus(); } bool LiteralBase::Piece::IsKnown() const { if (array_value_state_ != ArrayValueState::kKnown) { return false; } if (subshape().IsTuple()) { bool are_all_leaf_arrays_known = true; ForEachSubpiece([&are_all_leaf_arrays_known](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_known &= piece.IsKnown(); }); return are_all_leaf_arrays_known; } return true; } ForEachSubpiece([&are_all_leaf_arrays_known](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_known &= piece.IsKnown(); }); bool LiteralBase::Piece::IsDetermined() const { if (array_value_state_ == ArrayValueState::kUndetermined) { return false; } if (subshape().IsTuple()) { bool are_all_leaf_arrays_determined = true; ForEachSubpiece([&are_all_leaf_arrays_determined](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_determined &= piece.IsDetermined(); }); return are_all_leaf_arrays_determined; } return true; } ForEachSubpiece([&are_all_leaf_arrays_determined](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_determined &= piece.IsDetermined(); }); LiteralProto LiteralBase::ToProto() const { LiteralProto proto; root_piece().ForEachSubpiece( [&](const ShapeIndex& index, const Piece& piece) { LiteralProto* proto_piece = &proto; for (int64_t i : index) { while (proto_piece->tuple_literals_size() <= i) { proto_piece->add_tuple_literals(); } proto_piece = proto_piece->mutable_tuple_literals(i); } piece.WriteToProto(proto_piece); }); return proto; } [&](const ShapeIndex& index, const Piece& piece) { LiteralProto* proto_piece = &proto; for (int64_t i : index) { while (proto_piece->tuple_literals_size() <= i) { proto_piece->add_tuple_literals(); } proto_piece = proto_piece->mutable_tuple_literals(i); } piece.WriteToProto(proto_piece); }); const void* LiteralBase::untyped_data(const ShapeIndex& shape_index) const { return piece(shape_index).untyped_data(); } void* MutableLiteralBase::untyped_data(const ShapeIndex& shape_index) { return piece(shape_index).untyped_data(); } int64_t LiteralBase::size_bytes(const ShapeIndex& shape_index) const { return piece(shape_index).size_bytes_dense(); } std::string LiteralBase::GetR1U8AsString() const { CHECK(shape().IsArray()); CHECK_EQ(shape().rank(), 1); CHECK_EQ(shape().element_type(), U8); return std::string(absl::bit_cast<const char*>(data<uint8_t>().data()), ShapeUtil::ElementsIn(shape())); } void MutableBorrowingLiteral::CopyPieceSubtree(const Shape& shape, const Piece* src_piece, Piece* dest_piece) { DCHECK(ShapeUtil::Equal(src_piece->subshape(), dest_piece->subshape())) << "src_piece has shape: " << ShapeUtil::HumanString(src_piece->subshape()) << "dest_piece has shape: " << ShapeUtil::HumanString(dest_piece->subshape()); dest_piece->set_array_value_state(src_piece->get_array_value_state()); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); Piece child_piece; child_piece.set_subshape(&subshape); CopyPieceSubtree(subshape, &src_piece->child(i), &child_piece); dest_piece->emplace_back(std::move(child_piece)); } } else if (shape.IsArray()) { dest_piece->set_buffer(const_cast<char*>(src_piece->buffer())); } } MutableLiteralBase::~MutableLiteralBase() = default; MutableBorrowingLiteral::MutableBorrowingLiteral( const MutableBorrowingLiteral& literal) : MutableLiteralBase() { shape_ = literal.shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.root_piece(), root_piece_); } MutableBorrowingLiteral& MutableBorrowingLiteral::operator=( const MutableBorrowingLiteral& literal) { shape_ = literal.shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.root_piece(), root_piece_); return *this; } MutableBorrowingLiteral::MutableBorrowingLiteral(MutableLiteralBase* literal) : MutableLiteralBase() { shape_ = literal->shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal->root_piece(), root_piece_); } MutableBorrowingLiteral::MutableBorrowingLiteral( MutableBorrowingLiteral literal, const ShapeIndex& view_root) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(literal.piece(view_root).subshape()); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.piece(view_root), root_piece_); } MutableBorrowingLiteral::MutableBorrowingLiteral(const char* src_buf_ptr, const Shape& shape) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(shape); CHECK(LayoutUtil::HasLayout(*shape_)); CHECK(!shape_->IsTuple()); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); root_piece_->set_buffer(const_cast<char*>(src_buf_ptr)); } MutableBorrowingLiteral::MutableBorrowingLiteral(absl::Span<char*> src_buf_ptrs, const Shape& shape) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(shape); if (!shape_->IsTuple()) { CHECK_EQ(src_buf_ptrs.size(), 1); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); root_piece_->set_buffer(const_cast<char*>(src_buf_ptrs[0])); } else { CHECK(!ShapeUtil::IsNestedTuple(*shape_)); CHECK_EQ(src_buf_ptrs.size(), ShapeUtil::TupleElementCount(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); for (int i = 0; i < src_buf_ptrs.size(); ++i) { Piece child_piece; const auto& src_shape = shape_->tuple_shapes(i); CHECK(src_shape.IsArray()); child_piece.set_subshape(&src_shape); child_piece.set_buffer(src_buf_ptrs[i]); root_piece_->emplace_back(std::move(child_piece)); } } } MutableBorrowingLiteral::MutableBorrowingLiteral(ShapeTree<char*> src_buf_ptrs) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(src_buf_ptrs.shape()); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); BuildPieceSubtree(*shape_, root_piece_); root_piece_->ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); } [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); MutableBorrowingLiteral::~MutableBorrowingLiteral() { if (root_piece_ != nullptr) { delete root_piece_; } } LiteralSlice::LiteralSlice(const LiteralBase& literal) : LiteralBase(), root_piece_(&literal.root_piece()) {} LiteralSlice::LiteralSlice(const LiteralBase& literal, const ShapeIndex& view_root) : LiteralBase(), root_piece_(&literal.piece(view_root)) {} BorrowingLiteral::BorrowingLiteral(const char* src_buf_ptr, const Shape& shape) : LiteralBase(), shape_(std::make_unique<Shape>(shape)) { CHECK(shape_->IsArray()); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); root_piece_.set_buffer(const_cast<char*>(src_buf_ptr)); } BorrowingLiteral::BorrowingLiteral(absl::Span<const char* const> src_buf_ptrs, const Shape& shape) : LiteralBase(), shape_(std::make_unique<Shape>(shape)) { CHECK(shape_->IsTuple()); CHECK(!ShapeUtil::IsNestedTuple(*shape_)); CHECK_EQ(src_buf_ptrs.size(), ShapeUtil::TupleElementCount(*shape_)); root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); BuildPieceSubtree(*shape_, &root_piece_); for (int i = 0, end = src_buf_ptrs.size(); i < end; ++i) { const auto& src_shape = shape_->tuple_shapes(i); CHECK(src_shape.IsArray()); root_piece_.child(i).set_buffer(const_cast<char*>(src_buf_ptrs[i])); } } BorrowingLiteral::BorrowingLiteral(ShapeTree<const char*> src_buf_ptrs) : LiteralBase(), shape_(std::make_unique<Shape>(src_buf_ptrs.shape())) { root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); BuildPieceSubtree(*shape_, &root_piece_); root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); } [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); });
#include "xla/literal.h" #include <algorithm> #include <cmath> #include <complex> #include <cstdint> #include <functional> #include <limits> #include <random> #include <string> #include <tuple> #include <utility> #include <vector> #include "absl/base/casts.h" #include "absl/hash/hash.h" #include "absl/random/random.h" #include "absl/status/status.h" #include "absl/strings/match.h" #include "absl/types/span.h" #include "xla/array.h" #include "xla/array2d.h" #include "xla/array3d.h" #include "xla/array4d.h" #include "xla/index_util.h" #include "xla/layout.h" #include "xla/layout_util.h" #include "xla/literal_util.h" #include "xla/primitive_util.h" #include "xla/shape.h" #include "xla/shape_tree.h" #include "xla/shape_util.h" #include "xla/test.h" #include "xla/types.h" #include "xla/util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/errors.h" #include "tsl/platform/logging.h" // IWYU pragma: keep #include "tsl/platform/macros.h" #include "tsl/platform/ml_dtypes.h" #include "tsl/platform/statusor.h" #include "tsl/platform/test_benchmark.h" class LiteralUtilTest : public ::testing::Test { protected: LiteralUtilTest() { Array4D<float> arr4d({ // clang-format off { // i0=0 { // i1=0 {1, 2, 3}, // i2=0 {4, 5, 6}, // i2=1 {7, 8, 9}, // i2=2 }, { // i1=1 {11, 12, 13}, {14, 15, 16}, {17, 18, 19}, }, }, { // i0=1 { // i1=0 {101, 102, 103}, {104, 105, 106}, {107, 108, 109}, }, { // i1=1 {201, 202, 203}, // i2=0 {204, 205, 206}, // i2=1 {207, 208, 209}, // i2=2 }, }, // clang-format on }); layout_r2_dim0major_ = LayoutUtil::MakeLayout({1, 0}); layout_r2_dim0minor_ = LayoutUtil::MakeLayout({0, 1}); layout_r3_dim0major_ = LayoutUtil::MakeLayout({2, 1, 0}); layout_r3_dim0minor_ = LayoutUtil::MakeLayout({0, 1, 2}); layout_r4_dim0major_ = LayoutUtil::MakeLayout({3, 2, 1, 0}); layout_r4_dim0minor_ = LayoutUtil::MakeLayout({0, 1, 2, 3}); literal_r4_2x2x3x3_dim0major_ = LiteralUtil::CreateR4FromArray4DWithLayout<float>(arr4d, layout_r4_dim0major_); literal_r4_2x2x3x3_dim0minor_ = LiteralUtil::CreateR4FromArray4DWithLayout<float>(arr4d, layout_r4_dim0minor_); } Layout layout_r2_dim0major_; Layout layout_r2_dim0minor_; Layout layout_r3_dim0major_; Layout layout_r3_dim0minor_; Layout layout_r4_dim0major_; Layout layout_r4_dim0minor_; Literal literal_r4_2x2x3x3_dim0major_; Literal literal_r4_2x2x3x3_dim0minor_; }; TEST_F(LiteralUtilTest, BitcastConvert) { Literal original = LiteralUtil::CreateR1<uint32_t>( {absl::bit_cast<uint32_t>(2.5f), absl::bit_cast<uint32_t>(-42.25f), absl::bit_cast<uint32_t>(100.f), 0xbeef}); Literal expected = LiteralUtil::CreateR1<float>( {2.5f, -42.25f, 100.0f, absl::bit_cast<float>(0xbeef)}); TF_ASSERT_OK_AND_ASSIGN(Literal converted, original.BitcastConvert(ShapeUtil::ChangeElementType( original.shape(), F32))); }
LiteralUtilTest_BitcastConvertBetweenInvalidTypes
xla/literal_test.cc
bool LiteralProtoHasValues(const LiteralProto& proto) { return !proto.s2s().empty() || !proto.s4s().empty() || !proto.s8s().empty() || !proto.s16s().empty() || proto.s32s_size() || proto.s64s_size() || !proto.u2s().empty() || !proto.u4s().empty() || !proto.u8s().empty() || !proto.u16s().empty() || proto.u32s_size() || proto.u64s_size() || !proto.f8e5m2s().empty() || !proto.f8e4m3fns().empty() || !proto.f8e4m3b11fnuzs().empty() || !proto.f8e5m2fnuzs().empty() || !proto.f8e4m3fnuzs().empty() || !proto.f16s().empty() || !proto.bf16s().empty() || proto.f32s_size() || proto.f64s_size() || proto.c64s_size() || proto.c128s_size() || proto.preds_size() || proto.tuple_literals_size(); } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { const Shape& NilShape() { static const Shape* shape = new Shape(TUPLE, {}, {}, {}); return *shape; } const Shape* TryInternShape(const Shape& shape) { if (shape.IsTuple() && shape.tuple_shapes_size() == 0) { return &NilShape(); } if (shape.IsArray() && shape.dimensions_size() == 0 && shape.is_static() && shape.layout().tiles_size() == 0 && shape.layout().memory_space() == 0) { return &ScalarShape(shape.element_type()); } return nullptr; } StrideConfig::StrideConfig(const Shape& source_shape, const Shape& dest_shape, absl::Span<const int64_t> dimensions) : dimensions(dimensions), base(dimensions.size(), 0), step(dimensions.size(), 1) { if (!dimensions.empty()) { // Selects the shape with the largest minor dimension as the one upon // which to run the tight stride loop. if (dimensions[LayoutUtil::Minor(source_shape.layout(), 0)] >= dimensions[LayoutUtil::Minor(dest_shape.layout(), 0)]) { minor_dimension = LayoutUtil::Minor(source_shape.layout(), 0); dest_stride = IndexUtil::GetDimensionStride(dest_shape, minor_dimension); } else { minor_dimension = LayoutUtil::Minor(dest_shape.layout(), 0); source_stride = IndexUtil::GetDimensionStride(source_shape, minor_dimension); } minor_loop_size = dimensions[minor_dimension]; step[minor_dimension] = minor_loop_size; } } LiteralBase::~LiteralBase() = default; const Shape& LiteralBase::shape() const { return root_piece().subshape(); } const char* LiteralBase::Piece::buffer() const { // std::visit is avoided here due to its code size issues. if (auto* r = std::get_if<DenseRep>(&rep_)) { return r->data; } if (auto* r = std::get_if<DenseInlinedRep>(&rep_)) { return r->data; } DCHECK(std::holds_alternative<TupleRep>(rep_) || std::holds_alternative<Uninitialized>(rep_)); return nullptr; } const LiteralBase::Piece& LiteralBase::piece( const ShapeIndex& shape_index) const { const Piece* piece = &root_piece(); for (const auto i : shape_index) { DCHECK_GE(i, 0); DCHECK_LT(i, piece->children_size()); piece = &piece->child(i); } return *piece; } std::ostream& operator<<(std::ostream& out, const Literal& literal) { out << literal.ToString(); return out; } Shape* MutableLiteralBase::mutable_shape_do_not_use() { const Shape* const_shape = shape_.get(); if (!shape_.OwnsPtr()) { shape_ = MaybeOwningShapePtr(std::make_unique<Shape>(*shape_)); } Shape* shape = shape_.get_mutable(); if (shape != const_shape) { std::function<void(const Shape&, Piece*)> set_piece_shapes = [&set_piece_shapes](const Shape& shape, Piece* piece) { piece->set_subshape(&shape); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); set_piece_shapes(subshape, &piece->child(i)); } } }; set_piece_shapes(*shape, &mutable_root_piece()); } return shape; } [&set_piece_shapes](const Shape& shape, Piece* piece) { piece->set_subshape(&shape); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); set_piece_shapes(subshape, &piece->child(i)); } } }; Literal::Literal() : Literal(NilShape()) {} Literal::Literal(const Shape& shape) : Literal(shape, /*allocate_arrays=*/true) {} void Literal::SetShape(const Shape& shape) { Shape shape_storage; const Shape* shape_ptr = &shape; if (LayoutUtil::HasCustomElementSizeInBits(shape)) { shape_storage = shape; shape_storage.mutable_layout()->set_element_size_in_bits(0); shape_ptr = &shape_storage; } if (const Shape* intered_shape_ptr = TryInternShape(*shape_ptr)) { shape_ = intered_shape_ptr; } else { shape_ = std::make_unique<Shape>(*shape_ptr); } } void Literal::SetPiece(const Shape& shape, Piece* piece, bool allocate_arrays, ArrayValueState leaf_array_value_state) { if (shape.IsTuple()) { for (const Shape& subshape : shape.tuple_shapes()) { Piece child_piece; child_piece.set_subshape(&subshape); SetPiece(subshape, &child_piece, allocate_arrays, leaf_array_value_state); piece->emplace_back(std::move(child_piece)); } } else if (shape.IsArray()) { DCHECK(LayoutUtil::IsDenseArray(shape)) << "literal array storage is currently only supported for dense " "arrays: " << shape; piece->set_array_value_state(leaf_array_value_state); if (leaf_array_value_state == LiteralBase::ArrayValueState::kKnown && allocate_arrays) { piece->AllocateBuffers(); } } } Literal::Literal(const Shape& shape, bool allocate_arrays, ArrayValueState leaf_array_value_state) : MutableLiteralBase() { SetShape(shape); CHECK(leaf_array_value_state != ArrayValueState::kKnown || LayoutUtil::HasLayout(*shape_)); root_piece_.set_subshape(shape_.get()); CHECK(&root_piece_.subshape() == shape_.get()); SetPiece(*shape_, &root_piece_, allocate_arrays, leaf_array_value_state); } Literal::~Literal() { DeallocateBuffers(); } void Literal::DeallocateBuffers() { root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { piece->DeallocateBuffers(); }); } Literal::Literal(Literal&& other) : MutableLiteralBase() { *this = std::move(other); } Literal& Literal::operator=(Literal&& other) { DCHECK(&other.root_piece_.subshape() == other.shape_.get()); using std::swap; swap(shape_, other.shape_); swap(root_piece_, other.root_piece_); DCHECK(&root_piece_.subshape() == shape_.get()); return *this; } Literal LiteralBase::CreateFromShape(const Shape& shape) { Literal literal(shape); literal.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (piece->subshape().IsArray()) { memset(piece->untyped_data(), 0, piece->size_bytes_dense()); } }); return literal; } [&](const ShapeIndex& index, Piece* piece) { if (piece->subshape().IsArray()) { memset(piece->untyped_data(), 0, piece->size_bytes_dense()); } }); Literal LiteralBase::CreateFromShapeWithUnknownLeafArrays(const Shape& shape) { Literal literal(shape, /*allocate_arrays=*/false, ArrayValueState::kUnknown); return literal; } Literal LiteralBase::CreateFromShapeWithUndeterminedLeafArrays( const Shape& shape) { Literal literal(shape, /*allocate_arrays=*/false, ArrayValueState::kUndetermined); return literal; } int32_t LiteralBase::GetDynamicSize(int64_t dim_index) const { return GetDynamicSize(dim_index, {}); } int32_t LiteralBase::GetDynamicSize(int64_t dim_index, const ShapeIndex& shape_index) const { return piece(shape_index).GetDynamicSize(dim_index); } std::optional<int64_t> LiteralBase::GetFirstInteger() const { if (!primitive_util::IsIntegralType(shape().element_type())) { return std::nullopt; } return primitive_util::IntegralTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, void LiteralBase::BuildPieceSubtree(const Shape& shape, Piece* piece) { CHECK(shape.IsTuple()); for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); Piece child_piece; child_piece.set_subshape(&subshape); if (subshape.IsTuple()) { BuildPieceSubtree(subshape, &child_piece); } piece->emplace_back(std::move(child_piece)); } } absl::Status LiteralBase::SerializeToString(std::string* output) const { ShapeProto shape_proto = shape().ToProto(); TF_ASSIGN_OR_RETURN(int64_t size, ShapeUtil::SerializedSizeWithProto(shape(), shape_proto)); output->resize(size); return SerializeWithShapeProto(shape_proto, output->data()); } absl::StatusOr<std::string> LiteralBase::SerializeAsString() const { std::string result; TF_RETURN_IF_ERROR(SerializeToString(&result)); return std::move(result); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { void MutableLiteralBase::CopyElementFrom(const LiteralSlice& src_literal, absl::Span<const int64_t> src_index, absl::Span<const int64_t> dest_index) { DCHECK(LayoutUtil::IsDenseArray(shape())); DCHECK_EQ(shape().element_type(), src_literal.shape().element_type()); const int64_t src_linear_index = IndexUtil::MultidimensionalIndexToLinearIndex(src_literal.shape(), src_index); const int64_t dest_linear_index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), dest_index); const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); char* dest_address = static_cast<char*>(untyped_data()) + dest_linear_index * primitive_size; const char* source_address = static_cast<const char*>(src_literal.untyped_data()) + src_linear_index * primitive_size; if (dest_address != source_address) { memcpy(dest_address, source_address, primitive_size); } } /* static */ absl::StatusOr<Literal> MutableLiteralBase::CreateFromProto( const LiteralProto& proto, bool prohibit_empty_literal) { if (!proto.has_shape()) { return InvalidArgument("LiteralProto has no shape"); } Shape shape(proto.shape()); if (ShapeUtil::HasPrimitiveType(shape, OPAQUE_TYPE)) { return InvalidArgument( "Literal shape cannot include OPAQUE_TYPE sub-shape"); } if (!LayoutUtil::HasLayout(shape)) { return InvalidArgument("LiteralProto has no layout"); } if (LayoutUtil::IsSparseArray(shape)) { return Unimplemented("Sparse literals are not supported"); } TF_RETURN_IF_ERROR(ShapeUtil::ValidateShapeWithOptionalLayout(shape)); Literal literal(shape); TF_RETURN_IF_ERROR(literal.root_piece_.ForEachMutableSubpieceWithStatus( [&](const ShapeIndex& index, Piece* piece) -> absl::Status { const LiteralProto* proto_element = &proto; for (int64_t i : index) { CHECK(i < proto_element->tuple_literals_size()); proto_element = &proto_element->tuple_literals(i); } if (piece->subshape().IsTuple()) { if (proto_element->tuple_literals_size() != ShapeUtil::TupleElementCount(piece->subshape())) { return InvalidArgument( "Expected %d tuple elements in LiteralProto, has %d", ShapeUtil::TupleElementCount(piece->subshape()), proto_element->tuple_literals_size()); } return absl::OkStatus(); } if (piece->subshape().element_type() == TOKEN) { return absl::OkStatus(); } CHECK(piece->subshape().IsArray()); // When prohibit_empty_literal is false (allowing literal with no // values), only copy from proto if the literal proto has values. This // mode is used for a learned cost model. if (prohibit_empty_literal || LiteralProtoHasValues(*proto_element)) { TF_RETURN_IF_ERROR(piece->CopyFromProto(*proto_element)); } return absl::OkStatus(); })); return std::move(literal); } TF_RETURN_IF_ERROR(literal.root_piece_.ForEachMutableSubpieceWithStatus( Literal Literal::SubLiteral(ShapeIndexView shape_index) { if (!shape_index.empty()) { auto decomposed = this->DecomposeTuple(); return decomposed.at(shape_index.front()) .SubLiteral(shape_index.subspan(1)); } else { return std::move(*this); } } std::vector<Literal> Literal::DecomposeTuple() { CHECK(shape().IsTuple()); std::vector<Literal> elements; const auto tuple_element_count = ShapeUtil::TupleElementCount(shape()); elements.reserve(tuple_element_count); for (int i = 0; i < tuple_element_count; ++i) { elements.push_back(Literal(ShapeUtil::GetSubshape(shape(), {i}), /*allocate_arrays=*/false)); Literal& element = elements.back(); element.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* dest_piece) { if (dest_piece->subshape().IsTuple()) { return; } ShapeIndex src_index = {i}; for (int64_t j : index) { src_index.push_back(j); } Piece& src_piece = piece(src_index); // Move the respective buffer over to the element Literal. dest_piece->MoveDataFrom(src_piece); }); } // Set this literal to be nil-shaped. *this = Literal(); return elements; } [&](const ShapeIndex& index, Piece* dest_piece) { if (dest_piece->subshape().IsTuple()) { return; } ShapeIndex src_index = {i}; for (int64_t j : index) { src_index.push_back(j); } Piece& src_piece = piece(src_index); // Move the respective buffer over to the element Literal. dest_piece->MoveDataFrom(src_piece); }); void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } int32_t LiteralBase::Piece::GetDynamicSize(int64_t dim_index) const { CHECK(LayoutUtil::IsDenseArray(subshape())); if (!subshape_->is_dynamic_dimension(dim_index)) { // This is a static dimension, return size. return subshape_->dimensions(dim_index); } return dynamic_size_buffer()[dim_index]; } void LiteralBase::Piece::SetDynamicSize(int64_t dim_index, int32_t size) { CHECK(LayoutUtil::IsDenseArray(subshape())); CHECK(subshape_->is_dynamic_dimension(dim_index)); dynamic_size_buffer()[dim_index] = size; } void LiteralBase::Piece::AllocateBuffers() { const int64_t bytes = total_bytes_dense(); if (bytes > kMaxInlinedBytes) { CHECK_EQ(buffer(), nullptr); rep_.emplace<DenseRep>(); set_buffer( static_cast<char*>(tsl::port::AlignedMalloc(bytes, kMinimumAlignment))); } else { rep_.emplace<DenseInlinedRep>(); } } void LiteralBase::Piece::DeallocateBuffers() { if (auto* array_rep = GetDenseRep()) { tsl::port::AlignedFree(array_rep->data); rep_.emplace<Uninitialized>(); } } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } absl::Status LiteralBase::Piece::CopyFrom(const LiteralBase::Piece& src, bool only_dynamic_bound) { CHECK(subshape_ != nullptr); CHECK(src.subshape_ != nullptr); CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK(LayoutUtil::IsDenseArray(src.subshape())) << __func__ << " is only supported for dense arrays: " << src.subshape(); if (!only_dynamic_bound) { CHECK(ShapeUtil::Compatible(subshape(), src.subshape())); } if (src.array_value_state_ == ArrayValueState::kUnknown || src.array_value_state_ == ArrayValueState::kUndetermined) { if (array_value_state_ == ArrayValueState::kKnown) { DeallocateBuffers(); } array_value_state_ = src.array_value_state_; return absl::OkStatus(); } else { CHECK(src.array_value_state_ == ArrayValueState::kKnown); if (array_value_state_ == ArrayValueState::kUndetermined || array_value_state_ == ArrayValueState::kUnknown) { AllocateBuffers(); } array_value_state_ = src.array_value_state_; } if (ShapeUtil::Equal(subshape(), src.subshape())) { // If the layouts are equal it's faster just to memcpy. memcpy(buffer(), src.buffer(), src.size_bytes_dense()); } else { std::vector<int64_t> origin(subshape().rank(), 0); primitive_util::ArrayTypeSwitch<void>( [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, subshape().element_type()); } DCHECK_EQ(dynamic_size_buffer_bytes(), src.dynamic_size_buffer_bytes()); if (subshape().is_dynamic() && src.subshape().is_dynamic()) { memcpy(dynamic_size_buffer(), src.dynamic_size_buffer(), src.dynamic_size_buffer_bytes()); } return absl::OkStatus(); } [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, void MutableLiteralBase::SetDynamicSize(int64_t dim_index, int32_t size) { return SetDynamicSize(dim_index, {}, size); } void MutableLiteralBase::SetDynamicSize(int64_t dim_index, const ShapeIndex& shape_index, int32_t size) { Shape* subshape = ShapeUtil::GetMutableSubshape(mutable_shape_do_not_use(), shape_index); CHECK(LayoutUtil::IsDenseArray(*subshape)) << __func__ << " is only supported for dense arrays: " << *subshape; CHECK_GE(subshape->dimensions(dim_index), size); subshape->set_dynamic_dimension(dim_index, true); CHECK_EQ(&piece(shape_index).subshape(), subshape); piece(shape_index).SetDynamicSize(dim_index, size); } absl::Status MutableLiteralBase::CopyFrom(const LiteralSlice& src_literal, const ShapeIndex& dest_shape_index, const ShapeIndex& src_shape_index, bool only_dynamic_bound) { const Shape& dest_subshape = ShapeUtil::GetSubshape(shape(), dest_shape_index); const Shape& src_subshape = ShapeUtil::GetSubshape(src_literal.shape(), src_shape_index); if (only_dynamic_bound) { auto& bound_shape = dest_subshape.is_static() ? src_subshape : dest_subshape; auto& compact_shape = dest_subshape.is_static() ? dest_subshape : src_subshape; CHECK(ShapeUtil::DynamicShapeIsCompatible(compact_shape, bound_shape)) << compact_shape.ToString() << " vs " << bound_shape.ToString(); } else { if (!ShapeUtil::Compatible(dest_subshape, src_subshape)) { return InvalidArgument( "Destination subshape incompatible with source subshape: %s vs %s", ShapeUtil::HumanString(dest_subshape), ShapeUtil::HumanString(src_subshape)); } } return mutable_root_piece().ForEachMutableSubpieceWithStatus( [&](const ShapeIndex& index, Piece* piece) { if (!piece->subshape().IsArray()) { return absl::OkStatus(); } // Determine if this index is in the part of this literal that we want // to copy over from src_literal. bool in_subtree_to_copy = true; for (int i = 0; i < dest_shape_index.size(); ++i) { if (index[i] != dest_shape_index[i]) { in_subtree_to_copy = false; break; } } if (!in_subtree_to_copy) { return absl::OkStatus(); } // Construct the index of the corresponding piece in the source literal. ShapeIndex src_piece_index = src_shape_index; for (int64_t i = dest_shape_index.size(), end = index.size(); i < end; ++i) { src_piece_index.push_back(index[i]); } TF_RETURN_IF_ERROR( piece->CopyFrom(src_literal.piece(src_piece_index), /*only_dynamic_bound=*/only_dynamic_bound)); return absl::OkStatus(); }); } [&](const ShapeIndex& index, Piece* piece) { if (!piece->subshape().IsArray()) { return absl::OkStatus(); } // Determine if this index is in the part of this literal that we want // to copy over from src_literal. bool in_subtree_to_copy = true; for (int i = 0; i < dest_shape_index.size(); ++i) { if (index[i] != dest_shape_index[i]) { in_subtree_to_copy = false; break; } } if (!in_subtree_to_copy) { return absl::OkStatus(); } // Construct the index of the corresponding piece in the source literal. ShapeIndex src_piece_index = src_shape_index; for (int64_t i = dest_shape_index.size(), end = index.size(); i < end; ++i) { src_piece_index.push_back(index[i]); } TF_RETURN_IF_ERROR( piece->CopyFrom(src_literal.piece(src_piece_index), /*only_dynamic_bound=*/only_dynamic_bound)); return absl::OkStatus(); }); absl::Status Literal::MoveFrom(Literal&& src_literal, const ShapeIndex& dest_shape_index) { const Shape& dest_subshape = ShapeUtil::GetSubshape(shape(), dest_shape_index); if (!ShapeUtil::Equal(dest_subshape, src_literal.shape())) { return InvalidArgument( "Destination subshape not equal to source shape: %s vs %s", ShapeUtil::HumanString(dest_subshape), ShapeUtil::HumanString(src_literal.shape())); } src_literal.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& src_index, Piece* src_piece) { if (!src_piece->subshape().IsArray()) { return; } ShapeIndex dest_index = dest_shape_index; for (int64_t i : src_index) { dest_index.push_back(i); } Piece& dest_piece = piece(dest_index); dest_piece.DeallocateBuffers(); dest_piece.MoveDataFrom(*src_piece); }); src_literal.shape_ = MaybeOwningShapePtr(&NilShape()); src_literal.root_piece_ = Piece(); src_literal.root_piece_.set_subshape(src_literal.shape_.get()); return absl::OkStatus(); } [&](const ShapeIndex& src_index, Piece* src_piece) { if (!src_piece->subshape().IsArray()) { return; } ShapeIndex dest_index = dest_shape_index; for (int64_t i : src_index) { dest_index.push_back(i); } Piece& dest_piece = piece(dest_index); dest_piece.DeallocateBuffers(); dest_piece.MoveDataFrom(*src_piece); }); absl::Status MutableLiteralBase::CopySliceFrom( const LiteralSlice& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << shape(); TF_RET_CHECK(LayoutUtil::IsDenseArray(src_literal.shape())) << src_literal.shape(); TF_RET_CHECK(ShapeUtil::SameElementType(src_literal.shape(), shape())); TF_RET_CHECK(src_literal.shape().rank() == src_base.size()); TF_RET_CHECK(shape().rank() == dest_base.size()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, void MutableLiteralBase::PopulateR1(const tsl::core::Bitmap& values) { CHECK(shape().IsArray()); CHECK_EQ(shape().rank(), 1); CHECK_EQ(element_count(), values.bits()); CHECK_EQ(shape().element_type(), PRED); for (int64_t i = 0; i < static_cast<int64_t>(values.bits()); ++i) { Set({i}, values.get(i)); } } void MutableLiteralBase::PopulateInplaceInternal( absl::FunctionRef<void(void*, absl::Span<const int64_t>, int)> populator, bool parallel) { const Shape& this_shape = shape(); const int64_t rank = this_shape.rank(); DCHECK(LayoutUtil::IsDenseArray(this_shape)); char* const dest_base = static_cast<char*>(untyped_data()); if (rank > 0) { StrideConfig stride_config(this_shape, this_shape, this_shape.dimensions()); const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); const int64_t num_elements = ShapeUtil::ElementsIn(shape()); // If we are rank-1 and we are `parallel`, it is better to use a smaller // `step` than what `StrideConfig` does: stick the entire dimension in the // inner-most loop. if (parallel && this_shape.rank() == 1) { const int64_t thread_count = ShapeUtil::GetForEachIndexParallelThreadCount(); // Let's just divide up the array into small amounts per thread. stride_config.dest_stride = stride_config.minor_loop_size = num_elements > 32 ? std::max<int64_t>(num_elements / thread_count, 1) : num_elements; stride_config.step = {stride_config.minor_loop_size}; } auto init_function = [&](absl::Span<const int64_t> indexes, int thread_id) -> absl::StatusOr<bool> { const int64_t index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), indexes); DimensionVector minor_scan_indexes(rank, 0); std::copy(indexes.begin(), indexes.end(), minor_scan_indexes.begin()); char* dest_ptr = dest_base + index * primitive_size; char* const dest_end = dest_base + // This handles the case where minor_loop_size does not evenly divide // the most minor dimension. std::min(index + stride_config.minor_loop_size, num_elements) * primitive_size; while (dest_ptr < dest_end) { populator(dest_ptr, minor_scan_indexes, thread_id); ++minor_scan_indexes[stride_config.minor_dimension]; dest_ptr += primitive_size; } return true; }; if (parallel) { ShapeUtil::ForEachIndexParallel(this_shape, stride_config.base, stride_config.dimensions, stride_config.step, init_function); } else { ShapeUtil::ForEachIndex( this_shape, stride_config.base, stride_config.dimensions, stride_config.step, [&init_function]( absl::Span<const int64_t> indexes) -> absl::StatusOr<bool> { auto result_ignored = init_function(indexes, /*thread_id=*/-1); return true; }); } } else { // For scalars. populator(dest_base, {}, /*thread_id=*/-1); } } auto init_function = [&](absl::Span<const int64_t> indexes, int thread_id) -> absl::StatusOr<bool> { const int64_t index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), indexes); DimensionVector minor_scan_indexes(rank, 0); std::copy(indexes.begin(), indexes.end(), minor_scan_indexes.begin()); char* dest_ptr = dest_base + index * primitive_size; char* const dest_end = dest_base + // This handles the case where minor_loop_size does not evenly divide // the most minor dimension. std::min(index + stride_config.minor_loop_size, num_elements) * primitive_size; while (dest_ptr < dest_end) { populator(dest_ptr, minor_scan_indexes, thread_id); ++minor_scan_indexes[stride_config.minor_dimension]; dest_ptr += primitive_size; } return true; }; [&init_function]( absl::Span<const int64_t> indexes) -> absl::StatusOr<bool> { auto result_ignored = init_function(indexes, /*thread_id=*/-1); return true; }); absl::Status MutableLiteralBase::PopulateInplace( absl::FunctionRef<void(void*, absl::Span<const int64_t>)> populator) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); PopulateInplaceInternal( [&](void* dest, absl::Span<const int64_t> indexes, int /*thread_id*/) { return populator(dest, indexes); }, /*parallel=*/false); return absl::OkStatus(); } absl::Status MutableLiteralBase::PopulateInplaceParallel( absl::FunctionRef<void(void*, absl::Span<const int64_t>, int)> populator) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); PopulateInplaceInternal(populator, /*parallel=*/element_count() > 32); return absl::OkStatus(); } Literal LiteralBase::Relayout(const Layout& new_layout, const ShapeIndex& shape_index) const { // Create new shape with 'new_layout' set at the given shape index. Shape new_shape = shape(); Shape* subshape = ShapeUtil::GetMutableSubshape(&new_shape, shape_index); TF_CHECK_OK(LayoutUtil::ValidateLayoutForShape(new_layout, *subshape)); *subshape->mutable_layout() = new_layout; // LINT.IfChange // s4 literals are stored in uint8_t/int8_t, therefore element_size_in_bits // must be removed. if (subshape->layout().element_size_in_bits() == 4) { subshape->mutable_layout()->set_element_size_in_bits(0); } // LINT.ThenChange(//tensorflow/compiler/xla/types.h) Literal result(new_shape); TF_CHECK_OK(result.CopyFrom(*this)); return result; } Literal LiteralBase::Relayout(const Shape& shape_with_layout) const { CHECK(ShapeUtil::Compatible(shape_with_layout, shape())) << "Given shape_with_layout " << ShapeUtil::HumanString(shape_with_layout) << " not compatible with literal shape " << ShapeUtil::HumanString(shape()); Literal result = CreateFromShape(shape_with_layout); ShapeUtil::ForEachSubshape( result.shape(), [this, &result](const Shape& subshape, const ShapeIndex& index) { if (subshape.IsArray()) { TF_CHECK_OK(result.CopyFrom(*this, /*dest_shape_index=*/index, /*src_shape_index=*/index)); } }); return result; } [this, &result](const Shape& subshape, const ShapeIndex& index) { if (subshape.IsArray()) { TF_CHECK_OK(result.CopyFrom(*this, /*dest_shape_index=*/index, /*src_shape_index=*/index)); } }); Literal LiteralBase::ToBoundedDynamic(const Shape& bounded_shape) const { CHECK(bounded_shape.is_dynamic()); Literal result(bounded_shape); ShapeUtil::ForEachSubshape( shape(), [&](const Shape& subshape, const ShapeIndex& index) { if (!subshape.IsArray()) { return; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (bounded_shape.is_dynamic_dimension(i)) { result.SetDynamicSize(i, subshape.dimensions(i)); } } }); TF_CHECK_OK(result.CopyFrom(*this, {}, {}, /*only_dynamic_bound=*/true)); return result; } shape(), [&](const Shape& subshape, const ShapeIndex& index) { if (!subshape.IsArray()) { return; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (bounded_shape.is_dynamic_dimension(i)) { result.SetDynamicSize(i, subshape.dimensions(i)); } } }); Literal LiteralBase::ToStatic() const { // Create new shape with 'new_layout' set at the given shape index. Shape new_shape = shape(); ShapeUtil::ForEachMutableSubshape( &new_shape, [this](Shape* subshape, const ShapeIndex& index) { if (!subshape->IsArray()) { return; } for (int64_t i = 0; i < subshape->rank(); ++i) { // GetDynamicSize has a 32-bit return type and may truncate static // dimensions, so make sure to skip. if (!subshape->is_dynamic_dimension(i)) continue; subshape->set_dynamic_dimension(i, false); subshape->set_dimensions(i, GetDynamicSize(i, index)); } }); Literal result(new_shape); TF_CHECK_OK(result.CopyFrom(*this, {}, {}, /*only_dynamic_bound=*/true)); return result; } &new_shape, [this](Shape* subshape, const ShapeIndex& index) { if (!subshape->IsArray()) { return; } for (int64_t i = 0; i < subshape->rank(); ++i) { // GetDynamicSize has a 32-bit return type and may truncate static // dimensions, so make sure to skip. if (!subshape->is_dynamic_dimension(i)) continue; subshape->set_dynamic_dimension(i, false); subshape->set_dimensions(i, GetDynamicSize(i, index)); } }); absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { absl::StatusOr<Literal> LiteralBase::Broadcast( const Shape& result_shape, absl::Span<const int64_t> dimensions) const { const LiteralBase& src = *this; const Shape& src_shape = shape(); if (!src_shape.IsArray()) { return InvalidArgument("Broadcast only supports arrays."); } const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(src_shape.element_type()); switch (primitive_size) { case 0: return BroadcastHelper<0>(src, src_shape, result_shape, dimensions); case 1: return BroadcastHelper<1>(src, src_shape, result_shape, dimensions); case 2: return BroadcastHelper<2>(src, src_shape, result_shape, dimensions); case 4: return BroadcastHelper<4>(src, src_shape, result_shape, dimensions); case 8: return BroadcastHelper<8>(src, src_shape, result_shape, dimensions); case 16: return BroadcastHelper<16>(src, src_shape, result_shape, dimensions); default: LOG(FATAL) << "Unhandled primitive size " << primitive_size; return InvalidArgument("Unhandled primitive size"); break; } } absl::StatusOr<Literal> LiteralBase::Reshape( absl::Span<const int64_t> dimensions) const { if (!LayoutUtil::IsDenseArray(shape())) { return InvalidArgument("Reshape is only supported for dense arrays."); } if (shape().is_dynamic()) { // TODO(b/243182930): We should consider supporting dynamic reshape. return Unimplemented("Dynamic reshape is not implemented."); } Literal output; if (!LayoutUtil::IsMonotonicWithDim0Major(shape().layout())) { output = Relayout(LayoutUtil::GetDefaultLayoutForRank(shape().rank())); } else { output = Clone(); } // Because the layout is monotonic, we can simply reuse the same sequence of // values without changing their order. *output.mutable_shape_do_not_use() = ShapeUtil::MakeShape(shape().element_type(), dimensions); int64_t elements_before = ShapeUtil::ElementsIn(shape()); int64_t elements_after = ShapeUtil::ElementsIn(output.shape()); if (elements_before != elements_after) { return InvalidArgument( "Shapes before and after Literal::Reshape have different numbers " "of elements: %s vs %s.", ShapeUtil::HumanString(shape()), ShapeUtil::HumanString(output.shape())); } return std::move(output); } Literal LiteralBase::Transpose(absl::Span<const int64_t> permutation) const { CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); CHECK(shape().rank() == permutation.size() && IsPermutation(permutation)) << "Given permutation is not a permutation of dimension numbers"; // To transpose the array, we just permute the dimensions and layout, and // do a straight memory copy of the raw data set. // This is considerably faster than iterating over every array element using // the EachCell<>() and Set<>() APIs. Shape permuted_shape = ShapeUtil::PermuteDimensions(permutation, shape()); // Replace the layout with one affine to this shape, such that a // transpose operation can be performed by leaving the flat values // representation intact. // For example, consider the shape F32[11,8]{1,0} under a {1,0} permutation. // The shape with affine layout resulting from that operation will be // F32[8,11]{0,1}, since it leaves the original most minor (the 8 sized), the // most minor. // // Essentially, given MinMaj(Di) the position of the Di dimension within the // minor to major vector, and given T(Di) the index that the original Di // dimension has within the transposed array, a layout is affine if // MinMaj(Di) == TMinMaj(T(Di)), with TMinMaj() being the minor to major // vector of the affine layout. std::vector<int64_t> inverse_permutation = InversePermutation(permutation); CHECK(LayoutUtil::IsDenseArray(permuted_shape)); Layout* layout = permuted_shape.mutable_layout(); layout->clear_minor_to_major(); for (auto index : LayoutUtil::MinorToMajor(shape())) { layout->add_minor_to_major(inverse_permutation[index]); } Literal new_literal(permuted_shape); if (shape().is_dynamic()) { for (int64_t i = 0; i < shape().rank(); i++) { if (shape().is_dynamic_dimension(i)) { // Set the dynamic size of any dynamic dimension in the transposed // literal. new_literal.SetDynamicSize(inverse_permutation[i], GetDynamicSize(i)); } } } DCHECK_EQ(ShapeUtil::ByteSizeOf(new_literal.shape()), ShapeUtil::ByteSizeOf(shape())); std::memcpy(new_literal.untyped_data(), untyped_data(), size_bytes()); return new_literal; } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( Literal LiteralBase::Slice(absl::Span<const int64_t> start_indices, absl::Span<const int64_t> limit_indices) const { CHECK(shape().IsArray()) << "tuple is not supported for slice"; DimensionVector result_dimensions; for (int64_t dnum = 0; dnum < shape().rank(); ++dnum) { CHECK_GE(start_indices[dnum], 0); CHECK_LE(limit_indices[dnum], shape().dimensions(dnum)) << "dnum = " << dnum; int64_t dimension = limit_indices[dnum] - start_indices[dnum]; CHECK_GE(dimension, 0) << "dnum = " << dnum; result_dimensions.push_back(dimension); } auto result_shape = ShapeUtil::MakeShapeWithDenseLayout( shape().element_type(), result_dimensions, LayoutUtil::MinorToMajor(shape())); ShapeUtil::CopyDynamicDimensions(&result_shape, shape()); Literal result_literal(result_shape); primitive_util::ArrayTypeSwitch<void>( [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; return SliceInternal<NativeT>(*this, start_indices, result_literal); }, result_shape.element_type()); return result_literal; } Literal LiteralBase::Clone() const { Literal result(shape()); TF_CHECK_OK(result.CopyFrom(*this)); return result; } std::unique_ptr<Literal> LiteralBase::CloneToUnique() const { auto result = std::make_unique<Literal>(shape()); TF_CHECK_OK(result->CopyFrom(*this)); return result; } bool LiteralBase::IsDetermined(const ShapeIndex& shape_index) const { return piece(shape_index).IsDetermined(); } bool LiteralBase::IsKnown(const ShapeIndex& shape_index) const { return piece(shape_index).IsKnown(); } std::string LiteralBase::GetAsString(absl::Span<const int64_t> multi_index, const ShapeIndex& shape_index) const { const Shape& subshape = ShapeUtil::GetSubshape(shape(), shape_index); CHECK(LayoutUtil::IsDenseArray(subshape)); return primitive_util::ArrayTypeSwitch<std::string>( [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, subshape.element_type()); } [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, std::optional<int64_t> LiteralBase::GetIntegralAsS64( absl::Span<const int64_t> multi_index) const { CHECK(LayoutUtil::IsDenseArray(shape())); return primitive_util::PrimitiveTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, std::optional<double> LiteralBase::GetAsDouble( absl::Span<const int64_t> multi_index) const { const Shape& s = shape(); CHECK(LayoutUtil::IsDenseArray(s)); return primitive_util::PrimitiveTypeSwitch<std::optional<double>>( [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, s.element_type()); } [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, std::optional<double> LiteralBase::GetSumAsDouble( absl::Span<const int64_t> linear_indices) const { const Shape& s = shape(); CHECK(LayoutUtil::IsDenseArray(s)); if (!primitive_util::IsFloatingPointType(s.element_type())) { return std::nullopt; } return primitive_util::FloatingPointTypeSwitch<double>( [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, s.element_type()); } [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, std::optional<complex128> LiteralBase::GetAsComplex128( absl::Span<const int64_t> multi_index) const { return primitive_util::PrimitiveTypeSwitch<std::optional<complex128>>( [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, absl::Status MutableLiteralBase::SetIntegralAsS64( absl::Span<const int64_t> multi_index, int64_t value) { CHECK(LayoutUtil::IsDenseArray(shape())); return primitive_util::PrimitiveTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, absl::Status MutableLiteralBase::SetFromDouble( absl::Span<const int64_t> multi_index, double value) { CHECK(LayoutUtil::IsDenseArray(shape())); if (!primitive_util::IsFloatingPointType(shape().element_type())) { return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); } primitive_util::FloatingPointTypeSwitch<void>( [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, shape().element_type()); return absl::OkStatus(); } [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, void PrintShape(bool print_layout, const Shape& shape, Printer* printer) { if (print_layout) { ShapeUtil::PrintHumanStringWithLayout(printer, shape); } else { ShapeUtil::PrintHumanString(printer, shape); } } void TuplePrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); printer->Append(oneline ? "( " : "(\n"); for (int i = 0; i < ShapeUtil::TupleElementCount(subshape); ++i) { ShapeIndex element_index = shape_index; element_index.push_back(i); if (i > 0) printer->Append(oneline ? ", " : ",\n"); PrintHelper(literal, element_index, print_shape, print_layout, oneline, printer); } printer->Append(oneline ? " )" : "\n)"); } void DenseArrayPrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); int64_t rank = subshape.rank(); const absl::string_view linebreak = oneline ? " " : "\n"; std::function<void(absl::Span<const int64_t> dimensions, std::vector<int64_t>*)> print_recursive = [&](absl::Span<const int64_t> dimensions, std::vector<int64_t>* accum_indices) { // dimensions.size() decreases by 1 at each recursive call, // and accum_indices->size() increases by 1. // Their sum is equal to the rank of the tensor. CHECK_EQ(rank, dimensions.size() + accum_indices->size()); auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; if (dimensions.empty()) { // Display predicates as 0s and 1s so that the string is more dense. std::string elem; if (subshape.element_type() == PRED && rank > 0) { elem = literal.Get<bool>(*accum_indices, shape_index) ? "1" : "0"; } else { elem = literal.GetAsString(*accum_indices, shape_index); } printer->Append(elem); } else { printer->Append(brace_to_string("{")); for (int i = 0; i < dimensions[0]; ++i) { accum_indices->push_back(i); print_recursive(dimensions.subspan(1), accum_indices); accum_indices->pop_back(); if (i < dimensions[0] - 1) { printer->Append(","); printer->Append(dimensions.size() > 1 ? linebreak : " "); } } printer->Append(brace_to_string("}")); } }; if (print_shape) { PrintShape(print_layout, subshape, printer); if (subshape.is_dynamic()) { printer->Append("("); for (int64_t i = 0; i < subshape.dimensions_size(); ++i) { printer->Append(literal.GetDynamicSize(i, shape_index)); if (i < subshape.dimensions_size() - 1) { printer->Append(","); } } printer->Append(")"); } printer->Append(" "); } std::vector<int64_t> indices = {}; std::vector<int64_t> dimensions; dimensions.reserve(subshape.rank()); for (int64_t i = 0; i < subshape.rank(); ++i) { dimensions.push_back(literal.GetDynamicSize(i, shape_index)); } print_recursive(dimensions, &indices); } print_recursive = [&](absl::Span<const int64_t> dimensions, std::vector<int64_t>* accum_indices) { // dimensions.size() decreases by 1 at each recursive call, // and accum_indices->size() increases by 1. // Their sum is equal to the rank of the tensor. CHECK_EQ(rank, dimensions.size() + accum_indices->size()); auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; if (dimensions.empty()) { // Display predicates as 0s and 1s so that the string is more dense. std::string elem; if (subshape.element_type() == PRED && rank > 0) { elem = literal.Get<bool>(*accum_indices, shape_index) ? "1" : "0"; } else { elem = literal.GetAsString(*accum_indices, shape_index); } printer->Append(elem); } else { printer->Append(brace_to_string("{")); for (int i = 0; i < dimensions[0]; ++i) { accum_indices->push_back(i); print_recursive(dimensions.subspan(1), accum_indices); accum_indices->pop_back(); if (i < dimensions[0] - 1) { printer->Append(","); printer->Append(dimensions.size() > 1 ? linebreak : " "); } } printer->Append(brace_to_string("}")); } }; auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; void PrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); CHECK(LayoutUtil::HasLayout(literal.shape())); CHECK(LayoutUtil::HasLayout(subshape)); if (subshape.IsTuple()) { TuplePrintHelper(literal, shape_index, print_shape, print_layout, oneline, printer); } else if (subshape.IsToken()) { printer->Append("token"); } else { CHECK(LayoutUtil::IsDenseArray(subshape)); if (literal.IsKnown(shape_index)) { DenseArrayPrintHelper(literal, shape_index, print_shape, print_layout, oneline, printer); } else { PrintShape(print_layout, subshape, printer); printer->Append(" "); if (literal.IsDetermined(shape_index)) { printer->Append("unknown"); } else { printer->Append("undetermined"); } } } } void LiteralBase::Print(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/false, /*oneline=*/false, printer); } void LiteralBase::PrintOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/false, /*oneline=*/true, printer); } void LiteralBase::PrintWithoutShape(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/false, /*print_layout=*/false, /*oneline=*/false, printer); } void LiteralBase::PrintWithoutShapeOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/false, /*print_layout=*/false, /*oneline=*/true, printer); } void LiteralBase::PrintWithLayout(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/true, /*oneline=*/false, printer); } void LiteralBase::PrintWithLayoutOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/true, /*oneline=*/true, printer); } std::string LiteralBase::ToString() const { StringPrinter printer; Print(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringOneline() const { StringPrinter printer; PrintOneline(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithoutShape() const { StringPrinter printer; PrintWithoutShape(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithoutShapeOneline() const { StringPrinter printer; PrintWithoutShapeOneline(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithLayout() const { StringPrinter printer; PrintWithLayout(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithLayoutOneline() const { StringPrinter printer; PrintWithLayoutOneline(&printer); return std::move(printer).ToString(); } void LiteralBase::EachCellAsString( absl::FunctionRef<void(absl::Span<const int64_t> indices, const std::string& value)> per_cell) const { if (ShapeUtil::IsZeroElementArray(shape())) { return; } auto indices = IndexUtil::LinearIndexToMultidimensionalIndex( shape(), /*linear_index=*/0); do { per_cell(indices, GetAsString(indices)); } while (IndexUtil::BumpIndices(shape(), absl::MakeSpan(indices))); } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { absl::StatusOr<Literal> ConvertSwitch(const LiteralBase& literal, PrimitiveType primitive_dest_type) { TF_RET_CHECK(LayoutUtil::IsDenseArray(literal.shape())); if (literal.shape().element_type() == primitive_dest_type) { return literal.Clone(); } // Source Array type requirement is ensured by IsDenseArray before. if (!primitive_util::IsArrayType(primitive_dest_type) || !primitive_util::IsArrayType(literal.shape().element_type())) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(literal.shape().element_type()), PrimitiveType_Name(primitive_dest_type)); } // At this point, we know both src & dst are array types, while src is not // complex type, so we can allocate the result literal here to avoid // duplicating it N^2 times in the conversion implementation. Literal result( ShapeUtil::ChangeElementType(literal.shape(), primitive_dest_type)); TF_RETURN_IF_ERROR(primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { return ConvertIfDestTypeMatches<primitive_type_constant>(literal, result); }, literal.shape().element_type())); return result; } absl::StatusOr<Literal> LiteralBase::Convert( PrimitiveType primitive_dest_type) const { return ConvertSwitch(*this, primitive_dest_type); } absl::StatusOr<Literal> LiteralBase::BitcastConvert( const Shape& dest_shape) const { if (ShapeUtil::ByteSizeOf(dest_shape) != ShapeUtil::ByteSizeOf(shape())) { return InvalidArgument( "Can not bitcast-convert from shape %s to a shape of different size %s", shape().ToString(), dest_shape.ToString()); } if (dest_shape.IsTuple() || shape().IsTuple()) { return InvalidArgument( "bitcast-convert is not valid for tuple shapes %s->%s", shape().ToString(), dest_shape.ToString()); } if (shape().is_dynamic() || dest_shape.is_dynamic()) { return InvalidArgument( "bitcast-convert is not valid for dynamic shape %s->%s", shape().ToString(), dest_shape.ToString()); } Literal out(dest_shape); std::memcpy(out.root_piece_.buffer(), root_piece().buffer(), root_piece().size_bytes_dense()); // Perform the reshape on little endian encoding even on big endian machines. if constexpr (!kLittleEndian) { // Swap byte ordering as per the input data type. size_t input_elem_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); TF_RETURN_IF_ERROR(tsl::ByteSwapArray( const_cast<char*>(out.root_piece().buffer()), input_elem_size, out.root_piece().size_bytes_dense() / input_elem_size)); // Swap byte ordering as per the output data type. size_t output_elem_size = ShapeUtil::ByteSizeOfPrimitiveType(dest_shape.element_type()); TF_RETURN_IF_ERROR(tsl::ByteSwapArray( const_cast<char*>(out.root_piece().buffer()), output_elem_size, out.root_piece().size_bytes_dense() / output_elem_size)); } return out; } absl::StatusOr<Literal> LiteralBase::ConvertToShape( const Shape& dest_shape) const { if (!dest_shape.IsTuple()) { return Convert(dest_shape.element_type()); } std::vector<Literal> elements; const auto tuple_element_count = ShapeUtil::TupleElementCount(shape()); elements.reserve(tuple_element_count); for (int i = 0; i < tuple_element_count; ++i) { auto element = LiteralSlice(*this, {i}); TF_ASSIGN_OR_RETURN( auto new_element, element.ConvertToShape(ShapeUtil::GetSubshape(dest_shape, {i}))); elements.push_back(std::move(new_element)); } return MutableLiteralBase::MoveIntoTuple(absl::MakeSpan(elements)); } /* static */ Literal MutableLiteralBase::MoveIntoTuple( absl::Span<Literal> elements) { std::vector<const Shape*> element_shapes; element_shapes.reserve(elements.size()); for (const Literal& element : elements) { element_shapes.push_back(&element.shape()); } Literal literal(ShapeUtil::MakeTupleShapeWithPtrs(element_shapes), /*allocate_arrays=*/false); for (int i = 0, end = elements.size(); i < end; ++i) { TF_CHECK_OK( literal.MoveFrom(std::move(elements[i]), /*dest_shape_index=*/{i})); } return literal; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualDynamicSize( const LiteralBase::Piece& other) const { DCHECK(ShapeUtil::Compatible(subshape(), other.subshape())); if (subshape().is_static()) { return true; } for (int64_t i = 0; i < subshape().rank(); ++i) { if (GetDynamicSize(i) != other.GetDynamicSize(i)) { return false; } } return true; } bool LiteralBase::Piece::EqualElements(const LiteralBase::Piece& other) const { if (subshape().is_static() && ShapeUtil::Equal(subshape(), other.subshape()) && subshape().IsArray()) { CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(size_bytes_dense(), other.size_bytes_dense()); if (primitive_util::IsSubByteNonPredType(subshape().element_type())) { CHECK(!primitive_util::IsFloatingPointType(subshape().element_type())); auto one_array = buffer(); auto two_array = other.buffer(); const int bits_per_element = primitive_util::BitWidth(subshape().element_type()); const uint8_t mask = LsbMask<uint8_t>(bits_per_element); for (int64_t i = 0; i < size_bytes_dense(); ++i) { if ((one_array[i] & mask) != (two_array[i] & mask)) return false; } return true; } return memcmp(buffer(), other.buffer(), size_bytes_dense()) == 0; } std::vector<int64_t> multi_index; return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeSrcT = NativeTypeOf<primitive_type_constant>; return EqualElementsInternal<NativeSrcT>(other, &multi_index); }, subshape().element_type()); } bool LiteralBase::Equal(const LiteralBase& other, bool layout_sensitive) const { // Checking the structure of tuple literals. Checks for dense arrays are // performed below. if (!ShapeUtil::EqualStructure(shape(), other.shape())) { return false; } return root_piece().ForEachSubpieceWithBool([&](const ShapeIndex& index, const Piece& piece) { const Piece& other_piece = other.piece(index); const Shape& subshape = piece.subshape(); const Shape& other_subshape = other_piece.subshape(); if (subshape.element_type() != other_subshape.element_type()) { return false; } if (!piece.subshape().IsArray()) { return true; } if (subshape.rank() != other_subshape.rank()) { return false; } if (layout_sensitive && (subshape.layout() != other_subshape.layout())) { return false; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (piece.GetDynamicSize(i) != other_piece.GetDynamicSize(i)) { return false; } } if (!piece.EqualElements(other_piece)) { return false; } return true; }); } return root_piece().ForEachSubpieceWithBool([&](const ShapeIndex& index, const Piece& piece) { const Piece& other_piece = other.piece(index); const Shape& subshape = piece.subshape(); const Shape& other_subshape = other_piece.subshape(); if (subshape.element_type() != other_subshape.element_type()) { return false; } if (!piece.subshape().IsArray()) { return true; } if (subshape.rank() != other_subshape.rank()) { return false; } if (layout_sensitive && (subshape.layout() != other_subshape.layout())) { return false; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (piece.GetDynamicSize(i) != other_piece.GetDynamicSize(i)) { return false; } } if (!piece.EqualElements(other_piece)) { return false; } return true; }); static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(std::complex<T> a, std::complex<T> b) { return EqualIncludingNan(a.real(), b.real()) && EqualIncludingNan(a.imag(), b.imag()); } static bool EqualIncludingNan(std::complex<T> a, std::complex<T> b) { return EqualIncludingNan(a.real(), b.real()) && EqualIncludingNan(a.imag(), b.imag()); } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } bool Literal::Piece::IsAll(const Literal& scalar) const { CHECK(ShapeUtil::IsScalar(scalar.shape())) << scalar.shape().ToString(); if (!subshape().IsArray()) { return false; } CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(subshape().element_type(), scalar.shape().element_type()); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, subshape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, int64_t Literal::Piece::CountAll(const Literal& scalar) const { CHECK(ShapeUtil::IsScalar(scalar.shape())) << scalar.shape().ToString(); if (!subshape().IsArray()) { return 0; } CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(subshape().element_type(), scalar.shape().element_type()); return primitive_util::ArrayTypeSwitch<int64_t>( [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, subshape().element_type()); } [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { bool LiteralBase::IsAll(const Literal& scalar) const { return root_piece().IsAll(scalar); } bool LiteralBase::IsAll(int8_t value) const { if (!shape().IsArray()) { return false; } PrimitiveType ty = shape().element_type(); if (primitive_util::IsFloatingPointType(ty)) { return IsAllFloatImpl(value, /*round_value=*/false); } if (primitive_util::IsUnsignedIntegralType(ty) && value < 0) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllFloat(float value) const { return IsAllFloatImpl(value, /*round_value=*/true); } bool LiteralBase::IsAllFloatImpl(float value, bool round_value) const { PrimitiveType ty = shape().element_type(); if (!primitive_util::IsFloatingPointType(ty)) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::FloatingPointTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllComplex(complex64 value) const { PrimitiveType ty = shape().element_type(); if (!primitive_util::IsComplexType(ty)) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::ComplexTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllFirst() const { if (!shape().IsArray()) { return false; } // Empty shapes are not all the first element since there is no first element. if (ShapeUtil::IsZeroElementArray(shape())) { return false; } absl::InlinedVector<int64_t, 4> start_indices(/*n=*/shape().rank(), 0); absl::InlinedVector<int64_t, 4> end_indices(/*n=*/shape().rank(), 1); Literal first = Slice(start_indices, end_indices); return IsAll(first.Reshape({}).value()); } bool LiteralBase::IsR1Iota() const { if (!shape().IsArray()) { return false; } CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); if (shape().rank() != 1) { return false; } return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, shape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, std::optional<int64_t> LiteralBase::IsR1StridedIota() const { if (!shape().IsArray() || shape().rank() != 1) { return std::nullopt; } CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); const int64_t elements = ShapeUtil::ElementsIn(shape()); const PrimitiveType type = shape().element_type(); if (elements <= 1 || !primitive_util::IsIntegralType(type)) { return std::nullopt; } return primitive_util::IntegralTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, bool LiteralBase::IsZero(absl::Span<const int64_t> indices) const { CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, shape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void LiteralBase::Piece::set_array_value_state(ArrayValueState state) { array_value_state_ = state; } LiteralBase::ArrayValueState LiteralBase::Piece::get_array_value_state() const { return array_value_state_; } void LiteralBase::Piece::WriteToProto(LiteralProto* proto) const { *proto->mutable_shape() = subshape().ToProto(); switch (subshape().element_type()) { case PRED: CopyToRepeatedField(proto->mutable_preds(), data<bool>()); break; case U2: *proto->mutable_u2s() = std::string( reinterpret_cast<const char*>(data<u2>().data()), size_bytes_dense()); break; case U4: *proto->mutable_u4s() = std::string( reinterpret_cast<const char*>(data<u4>().data()), size_bytes_dense()); break; case U8: proto->set_u8s(static_cast<const unsigned char*>(data<uint8_t>().data()), element_count()); break; case U16: *proto->mutable_u16s() = std::string(reinterpret_cast<const char*>(data<uint16_t>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_u16s()); } break; case U32: CopyToRepeatedField(proto->mutable_u32s(), data<uint32_t>()); break; case U64: CopyToRepeatedField(proto->mutable_u64s(), data<uint64_t>()); break; case S2: *proto->mutable_s2s() = std::string( reinterpret_cast<const char*>(data<s2>().data()), size_bytes_dense()); break; case S4: *proto->mutable_s4s() = std::string( reinterpret_cast<const char*>(data<s4>().data()), size_bytes_dense()); break; case S8: proto->set_s8s(static_cast<const signed char*>(data<int8_t>().data()), element_count()); break; case S16: *proto->mutable_s16s() = std::string(reinterpret_cast<const char*>(data<int16_t>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_s16s()); } break; case S32: CopyToRepeatedField(proto->mutable_s32s(), data<int32_t>()); break; case S64: CopyToRepeatedField(proto->mutable_s64s(), data<int64_t>()); break; case F8E5M2: *proto->mutable_f8e5m2s() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e5m2>().data()), size_bytes_dense()); break; case F8E4M3FN: *proto->mutable_f8e4m3fns() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3fn>().data()), size_bytes_dense()); break; case F8E4M3B11FNUZ: *proto->mutable_f8e4m3b11fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3b11fnuz>().data()), size_bytes_dense()); break; case F8E5M2FNUZ: *proto->mutable_f8e5m2fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e5m2fnuz>().data()), size_bytes_dense()); break; case F8E4M3FNUZ: *proto->mutable_f8e4m3fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3fnuz>().data()), size_bytes_dense()); break; case F16: *proto->mutable_f16s() = std::string(reinterpret_cast<const char*>(data<half>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_f16s()); } break; case BF16: *proto->mutable_bf16s() = std::string(reinterpret_cast<const char*>(data<bfloat16>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_bf16s()); } break; case F32: CopyToRepeatedField(proto->mutable_f32s(), data<float>()); break; case F64: CopyToRepeatedField(proto->mutable_f64s(), data<double>()); break; case C64: for (complex64 value : data<complex64>()) { proto->add_c64s(value.real()); proto->add_c64s(value.imag()); } break; case C128: for (complex128 value : data<complex128>()) { proto->add_c128s(value.real()); proto->add_c128s(value.imag()); } break; case TUPLE: case TOKEN: // Nothing to do but assign the shape which is done above. return; default: // TODO(b/111551621): Support serializing more PrimitiveTypes. LOG(FATAL) << "Unhandled primitive type " << PrimitiveType_Name(subshape().element_type()); } } const void* LiteralBase::Piece::untyped_data() const { DCHECK(LayoutUtil::IsDenseArray(subshape())) << ShapeUtil::HumanString(subshape()); return buffer(); } void* LiteralBase::Piece::untyped_data() { DCHECK(LayoutUtil::IsDenseArray(subshape())) << ShapeUtil::HumanString(subshape()); return buffer(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status LiteralBase::Piece::CopyFromProto(const LiteralProto& proto) { // These conditions should have been checked in // MutableLiteralBase::CreateFromProto. TF_RET_CHECK(proto.has_shape()); Shape shape(proto.shape()); TF_RET_CHECK(LayoutUtil::HasLayout(shape)); TF_RET_CHECK(ShapeUtil::Equal(shape, subshape())); switch (subshape().element_type()) { case PRED: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<bool>(), proto.preds())); break; case S2: { const std::string& s(proto.s2s()); TF_RET_CHECK(data<s2>().size() * sizeof(s2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case S4: { const std::string& s(proto.s4s()); TF_RET_CHECK(data<s4>().size() * sizeof(s4) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case S8: { auto s8_data = data<int8_t>(); TF_RET_CHECK(proto.s8s().size() == s8_data.size()); std::copy(proto.s8s().begin(), proto.s8s().end(), s8_data.begin()); break; } case S16: { const std::string& s(proto.s16s()); TF_RET_CHECK(data<int16_t>().size() * sizeof(int16_t) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case S32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<int32_t>(), proto.s32s())); break; case S64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<int64_t>(), proto.s64s())); break; case U2: { const std::string& s(proto.u2s()); TF_RET_CHECK(data<u2>().size() * sizeof(u2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case U4: { const std::string& s(proto.u4s()); TF_RET_CHECK(data<u4>().size() * sizeof(u4) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case U8: { auto u8_data = data<uint8_t>(); TF_RET_CHECK(proto.u8s().size() == u8_data.size()); std::copy(proto.u8s().begin(), proto.u8s().end(), u8_data.begin()); break; } case U16: { const std::string& s(proto.u16s()); TF_RET_CHECK(data<uint16_t>().size() * sizeof(uint16_t) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case U32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<uint32_t>(), proto.u32s())); break; case U64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<uint64_t>(), proto.u64s())); break; case F8E5M2: { const std::string& s(proto.f8e5m2s()); TF_RET_CHECK(data<tsl::float8_e5m2>().size() * sizeof(tsl::float8_e5m2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3FN: { const std::string& s(proto.f8e4m3fns()); TF_RET_CHECK(data<tsl::float8_e4m3fn>().size() * sizeof(tsl::float8_e4m3fn) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3B11FNUZ: { const std::string& s(proto.f8e4m3b11fnuzs()); TF_RET_CHECK(data<tsl::float8_e4m3b11fnuz>().size() * sizeof(tsl::float8_e4m3b11fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E5M2FNUZ: { const std::string& s(proto.f8e5m2fnuzs()); TF_RET_CHECK(data<tsl::float8_e5m2fnuz>().size() * sizeof(tsl::float8_e5m2fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3FNUZ: { const std::string& s(proto.f8e4m3fnuzs()); TF_RET_CHECK(data<tsl::float8_e4m3fnuz>().size() * sizeof(tsl::float8_e4m3fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F16: { const std::string& s(proto.f16s()); TF_RET_CHECK(data<half>().size() * sizeof(half) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case BF16: { const std::string& s(proto.bf16s()); TF_RET_CHECK(data<bfloat16>().size() * sizeof(bfloat16) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case F32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<float>(), proto.f32s())); break; case F64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<double>(), proto.f64s())); break; case C64: { auto complex_data = data<complex64>(); TF_RET_CHECK(proto.c64s_size() == complex_data.size() * 2); for (int64_t i = 0; i < complex_data.size(); ++i) { complex_data[i] = complex64{proto.c64s(i * 2), proto.c64s(i * 2 + 1)}; } break; } case C128: { auto complex_data = data<complex128>(); const int64_t complex_data_size_doubled = complex_data.size() * 2; TF_RET_CHECK(proto.c128s_size() == complex_data_size_doubled); for (int64_t i = 0, end = complex_data.size(); i < end; ++i) { complex_data[i] = complex128{proto.c128s(i * 2), proto.c128s(i * 2 + 1)}; } break; } case TUPLE: return InvalidArgument("Should not be called on tuple shapes: %s", ShapeUtil::HumanString(subshape())); default: return InvalidArgument("Is called on unsupported shape: %s", ShapeUtil::HumanString(subshape())); } return absl::OkStatus(); } bool LiteralBase::Piece::IsKnown() const { if (array_value_state_ != ArrayValueState::kKnown) { return false; } if (subshape().IsTuple()) { bool are_all_leaf_arrays_known = true; ForEachSubpiece([&are_all_leaf_arrays_known](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_known &= piece.IsKnown(); }); return are_all_leaf_arrays_known; } return true; } ForEachSubpiece([&are_all_leaf_arrays_known](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_known &= piece.IsKnown(); }); bool LiteralBase::Piece::IsDetermined() const { if (array_value_state_ == ArrayValueState::kUndetermined) { return false; } if (subshape().IsTuple()) { bool are_all_leaf_arrays_determined = true; ForEachSubpiece([&are_all_leaf_arrays_determined](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_determined &= piece.IsDetermined(); }); return are_all_leaf_arrays_determined; } return true; } ForEachSubpiece([&are_all_leaf_arrays_determined](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_determined &= piece.IsDetermined(); }); LiteralProto LiteralBase::ToProto() const { LiteralProto proto; root_piece().ForEachSubpiece( [&](const ShapeIndex& index, const Piece& piece) { LiteralProto* proto_piece = &proto; for (int64_t i : index) { while (proto_piece->tuple_literals_size() <= i) { proto_piece->add_tuple_literals(); } proto_piece = proto_piece->mutable_tuple_literals(i); } piece.WriteToProto(proto_piece); }); return proto; } [&](const ShapeIndex& index, const Piece& piece) { LiteralProto* proto_piece = &proto; for (int64_t i : index) { while (proto_piece->tuple_literals_size() <= i) { proto_piece->add_tuple_literals(); } proto_piece = proto_piece->mutable_tuple_literals(i); } piece.WriteToProto(proto_piece); }); const void* LiteralBase::untyped_data(const ShapeIndex& shape_index) const { return piece(shape_index).untyped_data(); } void* MutableLiteralBase::untyped_data(const ShapeIndex& shape_index) { return piece(shape_index).untyped_data(); } int64_t LiteralBase::size_bytes(const ShapeIndex& shape_index) const { return piece(shape_index).size_bytes_dense(); } std::string LiteralBase::GetR1U8AsString() const { CHECK(shape().IsArray()); CHECK_EQ(shape().rank(), 1); CHECK_EQ(shape().element_type(), U8); return std::string(absl::bit_cast<const char*>(data<uint8_t>().data()), ShapeUtil::ElementsIn(shape())); } void MutableBorrowingLiteral::CopyPieceSubtree(const Shape& shape, const Piece* src_piece, Piece* dest_piece) { DCHECK(ShapeUtil::Equal(src_piece->subshape(), dest_piece->subshape())) << "src_piece has shape: " << ShapeUtil::HumanString(src_piece->subshape()) << "dest_piece has shape: " << ShapeUtil::HumanString(dest_piece->subshape()); dest_piece->set_array_value_state(src_piece->get_array_value_state()); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); Piece child_piece; child_piece.set_subshape(&subshape); CopyPieceSubtree(subshape, &src_piece->child(i), &child_piece); dest_piece->emplace_back(std::move(child_piece)); } } else if (shape.IsArray()) { dest_piece->set_buffer(const_cast<char*>(src_piece->buffer())); } } MutableLiteralBase::~MutableLiteralBase() = default; MutableBorrowingLiteral::MutableBorrowingLiteral( const MutableBorrowingLiteral& literal) : MutableLiteralBase() { shape_ = literal.shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.root_piece(), root_piece_); } MutableBorrowingLiteral& MutableBorrowingLiteral::operator=( const MutableBorrowingLiteral& literal) { shape_ = literal.shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.root_piece(), root_piece_); return *this; } MutableBorrowingLiteral::MutableBorrowingLiteral(MutableLiteralBase* literal) : MutableLiteralBase() { shape_ = literal->shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal->root_piece(), root_piece_); } MutableBorrowingLiteral::MutableBorrowingLiteral( MutableBorrowingLiteral literal, const ShapeIndex& view_root) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(literal.piece(view_root).subshape()); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.piece(view_root), root_piece_); } MutableBorrowingLiteral::MutableBorrowingLiteral(const char* src_buf_ptr, const Shape& shape) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(shape); CHECK(LayoutUtil::HasLayout(*shape_)); CHECK(!shape_->IsTuple()); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); root_piece_->set_buffer(const_cast<char*>(src_buf_ptr)); } MutableBorrowingLiteral::MutableBorrowingLiteral(absl::Span<char*> src_buf_ptrs, const Shape& shape) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(shape); if (!shape_->IsTuple()) { CHECK_EQ(src_buf_ptrs.size(), 1); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); root_piece_->set_buffer(const_cast<char*>(src_buf_ptrs[0])); } else { CHECK(!ShapeUtil::IsNestedTuple(*shape_)); CHECK_EQ(src_buf_ptrs.size(), ShapeUtil::TupleElementCount(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); for (int i = 0; i < src_buf_ptrs.size(); ++i) { Piece child_piece; const auto& src_shape = shape_->tuple_shapes(i); CHECK(src_shape.IsArray()); child_piece.set_subshape(&src_shape); child_piece.set_buffer(src_buf_ptrs[i]); root_piece_->emplace_back(std::move(child_piece)); } } } MutableBorrowingLiteral::MutableBorrowingLiteral(ShapeTree<char*> src_buf_ptrs) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(src_buf_ptrs.shape()); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); BuildPieceSubtree(*shape_, root_piece_); root_piece_->ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); } [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); MutableBorrowingLiteral::~MutableBorrowingLiteral() { if (root_piece_ != nullptr) { delete root_piece_; } } LiteralSlice::LiteralSlice(const LiteralBase& literal) : LiteralBase(), root_piece_(&literal.root_piece()) {} LiteralSlice::LiteralSlice(const LiteralBase& literal, const ShapeIndex& view_root) : LiteralBase(), root_piece_(&literal.piece(view_root)) {} BorrowingLiteral::BorrowingLiteral(const char* src_buf_ptr, const Shape& shape) : LiteralBase(), shape_(std::make_unique<Shape>(shape)) { CHECK(shape_->IsArray()); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); root_piece_.set_buffer(const_cast<char*>(src_buf_ptr)); } BorrowingLiteral::BorrowingLiteral(absl::Span<const char* const> src_buf_ptrs, const Shape& shape) : LiteralBase(), shape_(std::make_unique<Shape>(shape)) { CHECK(shape_->IsTuple()); CHECK(!ShapeUtil::IsNestedTuple(*shape_)); CHECK_EQ(src_buf_ptrs.size(), ShapeUtil::TupleElementCount(*shape_)); root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); BuildPieceSubtree(*shape_, &root_piece_); for (int i = 0, end = src_buf_ptrs.size(); i < end; ++i) { const auto& src_shape = shape_->tuple_shapes(i); CHECK(src_shape.IsArray()); root_piece_.child(i).set_buffer(const_cast<char*>(src_buf_ptrs[i])); } } BorrowingLiteral::BorrowingLiteral(ShapeTree<const char*> src_buf_ptrs) : LiteralBase(), shape_(std::make_unique<Shape>(src_buf_ptrs.shape())) { root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); BuildPieceSubtree(*shape_, &root_piece_); root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); } [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); });
#include "xla/literal.h" #include <algorithm> #include <cmath> #include <complex> #include <cstdint> #include <functional> #include <limits> #include <random> #include <string> #include <tuple> #include <utility> #include <vector> #include "absl/base/casts.h" #include "absl/hash/hash.h" #include "absl/random/random.h" #include "absl/status/status.h" #include "absl/strings/match.h" #include "absl/types/span.h" #include "xla/array.h" #include "xla/array2d.h" #include "xla/array3d.h" #include "xla/array4d.h" #include "xla/index_util.h" #include "xla/layout.h" #include "xla/layout_util.h" #include "xla/literal_util.h" #include "xla/primitive_util.h" #include "xla/shape.h" #include "xla/shape_tree.h" #include "xla/shape_util.h" #include "xla/test.h" #include "xla/types.h" #include "xla/util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/errors.h" #include "tsl/platform/logging.h" // IWYU pragma: keep #include "tsl/platform/macros.h" #include "tsl/platform/ml_dtypes.h" #include "tsl/platform/statusor.h" #include "tsl/platform/test_benchmark.h" class LiteralUtilTest : public ::testing::Test { protected: LiteralUtilTest() { Array4D<float> arr4d({ // clang-format off { // i0=0 { // i1=0 {1, 2, 3}, // i2=0 {4, 5, 6}, // i2=1 {7, 8, 9}, // i2=2 }, { // i1=1 {11, 12, 13}, {14, 15, 16}, {17, 18, 19}, }, }, { // i0=1 { // i1=0 {101, 102, 103}, {104, 105, 106}, {107, 108, 109}, }, { // i1=1 {201, 202, 203}, // i2=0 {204, 205, 206}, // i2=1 {207, 208, 209}, // i2=2 }, }, // clang-format on }); layout_r2_dim0major_ = LayoutUtil::MakeLayout({1, 0}); layout_r2_dim0minor_ = LayoutUtil::MakeLayout({0, 1}); layout_r3_dim0major_ = LayoutUtil::MakeLayout({2, 1, 0}); layout_r3_dim0minor_ = LayoutUtil::MakeLayout({0, 1, 2}); layout_r4_dim0major_ = LayoutUtil::MakeLayout({3, 2, 1, 0}); layout_r4_dim0minor_ = LayoutUtil::MakeLayout({0, 1, 2, 3}); literal_r4_2x2x3x3_dim0major_ = LiteralUtil::CreateR4FromArray4DWithLayout<float>(arr4d, layout_r4_dim0major_); literal_r4_2x2x3x3_dim0minor_ = LiteralUtil::CreateR4FromArray4DWithLayout<float>(arr4d, layout_r4_dim0minor_); } Layout layout_r2_dim0major_; Layout layout_r2_dim0minor_; Layout layout_r3_dim0major_; Layout layout_r3_dim0minor_; Layout layout_r4_dim0major_; Layout layout_r4_dim0minor_; Literal literal_r4_2x2x3x3_dim0major_; Literal literal_r4_2x2x3x3_dim0minor_; }; TEST_F(LiteralUtilTest, BitcastConvertBetweenInvalidTypes) { Literal literal = LiteralUtil::CreateR0<uint32_t>(1234); absl::Status status = literal.BitcastConvert(ShapeUtil::ChangeElementType(literal.shape(), F64)) .status(); EXPECT_NE(absl::OkStatus(), status); EXPECT_TRUE( absl::StrContains(status.message(), "to a shape of different size")); }
LiteralUtilTest_BorrowingLiteralFromMultipleBufferPtrs
xla/literal_test.cc
bool LiteralProtoHasValues(const LiteralProto& proto) { return !proto.s2s().empty() || !proto.s4s().empty() || !proto.s8s().empty() || !proto.s16s().empty() || proto.s32s_size() || proto.s64s_size() || !proto.u2s().empty() || !proto.u4s().empty() || !proto.u8s().empty() || !proto.u16s().empty() || proto.u32s_size() || proto.u64s_size() || !proto.f8e5m2s().empty() || !proto.f8e4m3fns().empty() || !proto.f8e4m3b11fnuzs().empty() || !proto.f8e5m2fnuzs().empty() || !proto.f8e4m3fnuzs().empty() || !proto.f16s().empty() || !proto.bf16s().empty() || proto.f32s_size() || proto.f64s_size() || proto.c64s_size() || proto.c128s_size() || proto.preds_size() || proto.tuple_literals_size(); } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { const Shape& NilShape() { static const Shape* shape = new Shape(TUPLE, {}, {}, {}); return *shape; } const Shape* TryInternShape(const Shape& shape) { if (shape.IsTuple() && shape.tuple_shapes_size() == 0) { return &NilShape(); } if (shape.IsArray() && shape.dimensions_size() == 0 && shape.is_static() && shape.layout().tiles_size() == 0 && shape.layout().memory_space() == 0) { return &ScalarShape(shape.element_type()); } return nullptr; } StrideConfig::StrideConfig(const Shape& source_shape, const Shape& dest_shape, absl::Span<const int64_t> dimensions) : dimensions(dimensions), base(dimensions.size(), 0), step(dimensions.size(), 1) { if (!dimensions.empty()) { // Selects the shape with the largest minor dimension as the one upon // which to run the tight stride loop. if (dimensions[LayoutUtil::Minor(source_shape.layout(), 0)] >= dimensions[LayoutUtil::Minor(dest_shape.layout(), 0)]) { minor_dimension = LayoutUtil::Minor(source_shape.layout(), 0); dest_stride = IndexUtil::GetDimensionStride(dest_shape, minor_dimension); } else { minor_dimension = LayoutUtil::Minor(dest_shape.layout(), 0); source_stride = IndexUtil::GetDimensionStride(source_shape, minor_dimension); } minor_loop_size = dimensions[minor_dimension]; step[minor_dimension] = minor_loop_size; } } LiteralBase::~LiteralBase() = default; const Shape& LiteralBase::shape() const { return root_piece().subshape(); } const char* LiteralBase::Piece::buffer() const { // std::visit is avoided here due to its code size issues. if (auto* r = std::get_if<DenseRep>(&rep_)) { return r->data; } if (auto* r = std::get_if<DenseInlinedRep>(&rep_)) { return r->data; } DCHECK(std::holds_alternative<TupleRep>(rep_) || std::holds_alternative<Uninitialized>(rep_)); return nullptr; } const LiteralBase::Piece& LiteralBase::piece( const ShapeIndex& shape_index) const { const Piece* piece = &root_piece(); for (const auto i : shape_index) { DCHECK_GE(i, 0); DCHECK_LT(i, piece->children_size()); piece = &piece->child(i); } return *piece; } std::ostream& operator<<(std::ostream& out, const Literal& literal) { out << literal.ToString(); return out; } Shape* MutableLiteralBase::mutable_shape_do_not_use() { const Shape* const_shape = shape_.get(); if (!shape_.OwnsPtr()) { shape_ = MaybeOwningShapePtr(std::make_unique<Shape>(*shape_)); } Shape* shape = shape_.get_mutable(); if (shape != const_shape) { std::function<void(const Shape&, Piece*)> set_piece_shapes = [&set_piece_shapes](const Shape& shape, Piece* piece) { piece->set_subshape(&shape); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); set_piece_shapes(subshape, &piece->child(i)); } } }; set_piece_shapes(*shape, &mutable_root_piece()); } return shape; } [&set_piece_shapes](const Shape& shape, Piece* piece) { piece->set_subshape(&shape); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); set_piece_shapes(subshape, &piece->child(i)); } } }; Literal::Literal() : Literal(NilShape()) {} Literal::Literal(const Shape& shape) : Literal(shape, /*allocate_arrays=*/true) {} void Literal::SetShape(const Shape& shape) { Shape shape_storage; const Shape* shape_ptr = &shape; if (LayoutUtil::HasCustomElementSizeInBits(shape)) { shape_storage = shape; shape_storage.mutable_layout()->set_element_size_in_bits(0); shape_ptr = &shape_storage; } if (const Shape* intered_shape_ptr = TryInternShape(*shape_ptr)) { shape_ = intered_shape_ptr; } else { shape_ = std::make_unique<Shape>(*shape_ptr); } } void Literal::SetPiece(const Shape& shape, Piece* piece, bool allocate_arrays, ArrayValueState leaf_array_value_state) { if (shape.IsTuple()) { for (const Shape& subshape : shape.tuple_shapes()) { Piece child_piece; child_piece.set_subshape(&subshape); SetPiece(subshape, &child_piece, allocate_arrays, leaf_array_value_state); piece->emplace_back(std::move(child_piece)); } } else if (shape.IsArray()) { DCHECK(LayoutUtil::IsDenseArray(shape)) << "literal array storage is currently only supported for dense " "arrays: " << shape; piece->set_array_value_state(leaf_array_value_state); if (leaf_array_value_state == LiteralBase::ArrayValueState::kKnown && allocate_arrays) { piece->AllocateBuffers(); } } } Literal::Literal(const Shape& shape, bool allocate_arrays, ArrayValueState leaf_array_value_state) : MutableLiteralBase() { SetShape(shape); CHECK(leaf_array_value_state != ArrayValueState::kKnown || LayoutUtil::HasLayout(*shape_)); root_piece_.set_subshape(shape_.get()); CHECK(&root_piece_.subshape() == shape_.get()); SetPiece(*shape_, &root_piece_, allocate_arrays, leaf_array_value_state); } Literal::~Literal() { DeallocateBuffers(); } void Literal::DeallocateBuffers() { root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { piece->DeallocateBuffers(); }); } Literal::Literal(Literal&& other) : MutableLiteralBase() { *this = std::move(other); } Literal& Literal::operator=(Literal&& other) { DCHECK(&other.root_piece_.subshape() == other.shape_.get()); using std::swap; swap(shape_, other.shape_); swap(root_piece_, other.root_piece_); DCHECK(&root_piece_.subshape() == shape_.get()); return *this; } Literal LiteralBase::CreateFromShape(const Shape& shape) { Literal literal(shape); literal.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (piece->subshape().IsArray()) { memset(piece->untyped_data(), 0, piece->size_bytes_dense()); } }); return literal; } [&](const ShapeIndex& index, Piece* piece) { if (piece->subshape().IsArray()) { memset(piece->untyped_data(), 0, piece->size_bytes_dense()); } }); Literal LiteralBase::CreateFromShapeWithUnknownLeafArrays(const Shape& shape) { Literal literal(shape, /*allocate_arrays=*/false, ArrayValueState::kUnknown); return literal; } Literal LiteralBase::CreateFromShapeWithUndeterminedLeafArrays( const Shape& shape) { Literal literal(shape, /*allocate_arrays=*/false, ArrayValueState::kUndetermined); return literal; } int32_t LiteralBase::GetDynamicSize(int64_t dim_index) const { return GetDynamicSize(dim_index, {}); } int32_t LiteralBase::GetDynamicSize(int64_t dim_index, const ShapeIndex& shape_index) const { return piece(shape_index).GetDynamicSize(dim_index); } std::optional<int64_t> LiteralBase::GetFirstInteger() const { if (!primitive_util::IsIntegralType(shape().element_type())) { return std::nullopt; } return primitive_util::IntegralTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, void LiteralBase::BuildPieceSubtree(const Shape& shape, Piece* piece) { CHECK(shape.IsTuple()); for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); Piece child_piece; child_piece.set_subshape(&subshape); if (subshape.IsTuple()) { BuildPieceSubtree(subshape, &child_piece); } piece->emplace_back(std::move(child_piece)); } } absl::Status LiteralBase::SerializeToString(std::string* output) const { ShapeProto shape_proto = shape().ToProto(); TF_ASSIGN_OR_RETURN(int64_t size, ShapeUtil::SerializedSizeWithProto(shape(), shape_proto)); output->resize(size); return SerializeWithShapeProto(shape_proto, output->data()); } absl::StatusOr<std::string> LiteralBase::SerializeAsString() const { std::string result; TF_RETURN_IF_ERROR(SerializeToString(&result)); return std::move(result); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { void MutableLiteralBase::CopyElementFrom(const LiteralSlice& src_literal, absl::Span<const int64_t> src_index, absl::Span<const int64_t> dest_index) { DCHECK(LayoutUtil::IsDenseArray(shape())); DCHECK_EQ(shape().element_type(), src_literal.shape().element_type()); const int64_t src_linear_index = IndexUtil::MultidimensionalIndexToLinearIndex(src_literal.shape(), src_index); const int64_t dest_linear_index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), dest_index); const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); char* dest_address = static_cast<char*>(untyped_data()) + dest_linear_index * primitive_size; const char* source_address = static_cast<const char*>(src_literal.untyped_data()) + src_linear_index * primitive_size; if (dest_address != source_address) { memcpy(dest_address, source_address, primitive_size); } } /* static */ absl::StatusOr<Literal> MutableLiteralBase::CreateFromProto( const LiteralProto& proto, bool prohibit_empty_literal) { if (!proto.has_shape()) { return InvalidArgument("LiteralProto has no shape"); } Shape shape(proto.shape()); if (ShapeUtil::HasPrimitiveType(shape, OPAQUE_TYPE)) { return InvalidArgument( "Literal shape cannot include OPAQUE_TYPE sub-shape"); } if (!LayoutUtil::HasLayout(shape)) { return InvalidArgument("LiteralProto has no layout"); } if (LayoutUtil::IsSparseArray(shape)) { return Unimplemented("Sparse literals are not supported"); } TF_RETURN_IF_ERROR(ShapeUtil::ValidateShapeWithOptionalLayout(shape)); Literal literal(shape); TF_RETURN_IF_ERROR(literal.root_piece_.ForEachMutableSubpieceWithStatus( [&](const ShapeIndex& index, Piece* piece) -> absl::Status { const LiteralProto* proto_element = &proto; for (int64_t i : index) { CHECK(i < proto_element->tuple_literals_size()); proto_element = &proto_element->tuple_literals(i); } if (piece->subshape().IsTuple()) { if (proto_element->tuple_literals_size() != ShapeUtil::TupleElementCount(piece->subshape())) { return InvalidArgument( "Expected %d tuple elements in LiteralProto, has %d", ShapeUtil::TupleElementCount(piece->subshape()), proto_element->tuple_literals_size()); } return absl::OkStatus(); } if (piece->subshape().element_type() == TOKEN) { return absl::OkStatus(); } CHECK(piece->subshape().IsArray()); // When prohibit_empty_literal is false (allowing literal with no // values), only copy from proto if the literal proto has values. This // mode is used for a learned cost model. if (prohibit_empty_literal || LiteralProtoHasValues(*proto_element)) { TF_RETURN_IF_ERROR(piece->CopyFromProto(*proto_element)); } return absl::OkStatus(); })); return std::move(literal); } TF_RETURN_IF_ERROR(literal.root_piece_.ForEachMutableSubpieceWithStatus( Literal Literal::SubLiteral(ShapeIndexView shape_index) { if (!shape_index.empty()) { auto decomposed = this->DecomposeTuple(); return decomposed.at(shape_index.front()) .SubLiteral(shape_index.subspan(1)); } else { return std::move(*this); } } std::vector<Literal> Literal::DecomposeTuple() { CHECK(shape().IsTuple()); std::vector<Literal> elements; const auto tuple_element_count = ShapeUtil::TupleElementCount(shape()); elements.reserve(tuple_element_count); for (int i = 0; i < tuple_element_count; ++i) { elements.push_back(Literal(ShapeUtil::GetSubshape(shape(), {i}), /*allocate_arrays=*/false)); Literal& element = elements.back(); element.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* dest_piece) { if (dest_piece->subshape().IsTuple()) { return; } ShapeIndex src_index = {i}; for (int64_t j : index) { src_index.push_back(j); } Piece& src_piece = piece(src_index); // Move the respective buffer over to the element Literal. dest_piece->MoveDataFrom(src_piece); }); } // Set this literal to be nil-shaped. *this = Literal(); return elements; } [&](const ShapeIndex& index, Piece* dest_piece) { if (dest_piece->subshape().IsTuple()) { return; } ShapeIndex src_index = {i}; for (int64_t j : index) { src_index.push_back(j); } Piece& src_piece = piece(src_index); // Move the respective buffer over to the element Literal. dest_piece->MoveDataFrom(src_piece); }); void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } int32_t LiteralBase::Piece::GetDynamicSize(int64_t dim_index) const { CHECK(LayoutUtil::IsDenseArray(subshape())); if (!subshape_->is_dynamic_dimension(dim_index)) { // This is a static dimension, return size. return subshape_->dimensions(dim_index); } return dynamic_size_buffer()[dim_index]; } void LiteralBase::Piece::SetDynamicSize(int64_t dim_index, int32_t size) { CHECK(LayoutUtil::IsDenseArray(subshape())); CHECK(subshape_->is_dynamic_dimension(dim_index)); dynamic_size_buffer()[dim_index] = size; } void LiteralBase::Piece::AllocateBuffers() { const int64_t bytes = total_bytes_dense(); if (bytes > kMaxInlinedBytes) { CHECK_EQ(buffer(), nullptr); rep_.emplace<DenseRep>(); set_buffer( static_cast<char*>(tsl::port::AlignedMalloc(bytes, kMinimumAlignment))); } else { rep_.emplace<DenseInlinedRep>(); } } void LiteralBase::Piece::DeallocateBuffers() { if (auto* array_rep = GetDenseRep()) { tsl::port::AlignedFree(array_rep->data); rep_.emplace<Uninitialized>(); } } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } absl::Status LiteralBase::Piece::CopyFrom(const LiteralBase::Piece& src, bool only_dynamic_bound) { CHECK(subshape_ != nullptr); CHECK(src.subshape_ != nullptr); CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK(LayoutUtil::IsDenseArray(src.subshape())) << __func__ << " is only supported for dense arrays: " << src.subshape(); if (!only_dynamic_bound) { CHECK(ShapeUtil::Compatible(subshape(), src.subshape())); } if (src.array_value_state_ == ArrayValueState::kUnknown || src.array_value_state_ == ArrayValueState::kUndetermined) { if (array_value_state_ == ArrayValueState::kKnown) { DeallocateBuffers(); } array_value_state_ = src.array_value_state_; return absl::OkStatus(); } else { CHECK(src.array_value_state_ == ArrayValueState::kKnown); if (array_value_state_ == ArrayValueState::kUndetermined || array_value_state_ == ArrayValueState::kUnknown) { AllocateBuffers(); } array_value_state_ = src.array_value_state_; } if (ShapeUtil::Equal(subshape(), src.subshape())) { // If the layouts are equal it's faster just to memcpy. memcpy(buffer(), src.buffer(), src.size_bytes_dense()); } else { std::vector<int64_t> origin(subshape().rank(), 0); primitive_util::ArrayTypeSwitch<void>( [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, subshape().element_type()); } DCHECK_EQ(dynamic_size_buffer_bytes(), src.dynamic_size_buffer_bytes()); if (subshape().is_dynamic() && src.subshape().is_dynamic()) { memcpy(dynamic_size_buffer(), src.dynamic_size_buffer(), src.dynamic_size_buffer_bytes()); } return absl::OkStatus(); } [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, void MutableLiteralBase::SetDynamicSize(int64_t dim_index, int32_t size) { return SetDynamicSize(dim_index, {}, size); } void MutableLiteralBase::SetDynamicSize(int64_t dim_index, const ShapeIndex& shape_index, int32_t size) { Shape* subshape = ShapeUtil::GetMutableSubshape(mutable_shape_do_not_use(), shape_index); CHECK(LayoutUtil::IsDenseArray(*subshape)) << __func__ << " is only supported for dense arrays: " << *subshape; CHECK_GE(subshape->dimensions(dim_index), size); subshape->set_dynamic_dimension(dim_index, true); CHECK_EQ(&piece(shape_index).subshape(), subshape); piece(shape_index).SetDynamicSize(dim_index, size); } absl::Status MutableLiteralBase::CopyFrom(const LiteralSlice& src_literal, const ShapeIndex& dest_shape_index, const ShapeIndex& src_shape_index, bool only_dynamic_bound) { const Shape& dest_subshape = ShapeUtil::GetSubshape(shape(), dest_shape_index); const Shape& src_subshape = ShapeUtil::GetSubshape(src_literal.shape(), src_shape_index); if (only_dynamic_bound) { auto& bound_shape = dest_subshape.is_static() ? src_subshape : dest_subshape; auto& compact_shape = dest_subshape.is_static() ? dest_subshape : src_subshape; CHECK(ShapeUtil::DynamicShapeIsCompatible(compact_shape, bound_shape)) << compact_shape.ToString() << " vs " << bound_shape.ToString(); } else { if (!ShapeUtil::Compatible(dest_subshape, src_subshape)) { return InvalidArgument( "Destination subshape incompatible with source subshape: %s vs %s", ShapeUtil::HumanString(dest_subshape), ShapeUtil::HumanString(src_subshape)); } } return mutable_root_piece().ForEachMutableSubpieceWithStatus( [&](const ShapeIndex& index, Piece* piece) { if (!piece->subshape().IsArray()) { return absl::OkStatus(); } // Determine if this index is in the part of this literal that we want // to copy over from src_literal. bool in_subtree_to_copy = true; for (int i = 0; i < dest_shape_index.size(); ++i) { if (index[i] != dest_shape_index[i]) { in_subtree_to_copy = false; break; } } if (!in_subtree_to_copy) { return absl::OkStatus(); } // Construct the index of the corresponding piece in the source literal. ShapeIndex src_piece_index = src_shape_index; for (int64_t i = dest_shape_index.size(), end = index.size(); i < end; ++i) { src_piece_index.push_back(index[i]); } TF_RETURN_IF_ERROR( piece->CopyFrom(src_literal.piece(src_piece_index), /*only_dynamic_bound=*/only_dynamic_bound)); return absl::OkStatus(); }); } [&](const ShapeIndex& index, Piece* piece) { if (!piece->subshape().IsArray()) { return absl::OkStatus(); } // Determine if this index is in the part of this literal that we want // to copy over from src_literal. bool in_subtree_to_copy = true; for (int i = 0; i < dest_shape_index.size(); ++i) { if (index[i] != dest_shape_index[i]) { in_subtree_to_copy = false; break; } } if (!in_subtree_to_copy) { return absl::OkStatus(); } // Construct the index of the corresponding piece in the source literal. ShapeIndex src_piece_index = src_shape_index; for (int64_t i = dest_shape_index.size(), end = index.size(); i < end; ++i) { src_piece_index.push_back(index[i]); } TF_RETURN_IF_ERROR( piece->CopyFrom(src_literal.piece(src_piece_index), /*only_dynamic_bound=*/only_dynamic_bound)); return absl::OkStatus(); }); absl::Status Literal::MoveFrom(Literal&& src_literal, const ShapeIndex& dest_shape_index) { const Shape& dest_subshape = ShapeUtil::GetSubshape(shape(), dest_shape_index); if (!ShapeUtil::Equal(dest_subshape, src_literal.shape())) { return InvalidArgument( "Destination subshape not equal to source shape: %s vs %s", ShapeUtil::HumanString(dest_subshape), ShapeUtil::HumanString(src_literal.shape())); } src_literal.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& src_index, Piece* src_piece) { if (!src_piece->subshape().IsArray()) { return; } ShapeIndex dest_index = dest_shape_index; for (int64_t i : src_index) { dest_index.push_back(i); } Piece& dest_piece = piece(dest_index); dest_piece.DeallocateBuffers(); dest_piece.MoveDataFrom(*src_piece); }); src_literal.shape_ = MaybeOwningShapePtr(&NilShape()); src_literal.root_piece_ = Piece(); src_literal.root_piece_.set_subshape(src_literal.shape_.get()); return absl::OkStatus(); } [&](const ShapeIndex& src_index, Piece* src_piece) { if (!src_piece->subshape().IsArray()) { return; } ShapeIndex dest_index = dest_shape_index; for (int64_t i : src_index) { dest_index.push_back(i); } Piece& dest_piece = piece(dest_index); dest_piece.DeallocateBuffers(); dest_piece.MoveDataFrom(*src_piece); }); absl::Status MutableLiteralBase::CopySliceFrom( const LiteralSlice& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << shape(); TF_RET_CHECK(LayoutUtil::IsDenseArray(src_literal.shape())) << src_literal.shape(); TF_RET_CHECK(ShapeUtil::SameElementType(src_literal.shape(), shape())); TF_RET_CHECK(src_literal.shape().rank() == src_base.size()); TF_RET_CHECK(shape().rank() == dest_base.size()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, void MutableLiteralBase::PopulateR1(const tsl::core::Bitmap& values) { CHECK(shape().IsArray()); CHECK_EQ(shape().rank(), 1); CHECK_EQ(element_count(), values.bits()); CHECK_EQ(shape().element_type(), PRED); for (int64_t i = 0; i < static_cast<int64_t>(values.bits()); ++i) { Set({i}, values.get(i)); } } void MutableLiteralBase::PopulateInplaceInternal( absl::FunctionRef<void(void*, absl::Span<const int64_t>, int)> populator, bool parallel) { const Shape& this_shape = shape(); const int64_t rank = this_shape.rank(); DCHECK(LayoutUtil::IsDenseArray(this_shape)); char* const dest_base = static_cast<char*>(untyped_data()); if (rank > 0) { StrideConfig stride_config(this_shape, this_shape, this_shape.dimensions()); const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); const int64_t num_elements = ShapeUtil::ElementsIn(shape()); // If we are rank-1 and we are `parallel`, it is better to use a smaller // `step` than what `StrideConfig` does: stick the entire dimension in the // inner-most loop. if (parallel && this_shape.rank() == 1) { const int64_t thread_count = ShapeUtil::GetForEachIndexParallelThreadCount(); // Let's just divide up the array into small amounts per thread. stride_config.dest_stride = stride_config.minor_loop_size = num_elements > 32 ? std::max<int64_t>(num_elements / thread_count, 1) : num_elements; stride_config.step = {stride_config.minor_loop_size}; } auto init_function = [&](absl::Span<const int64_t> indexes, int thread_id) -> absl::StatusOr<bool> { const int64_t index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), indexes); DimensionVector minor_scan_indexes(rank, 0); std::copy(indexes.begin(), indexes.end(), minor_scan_indexes.begin()); char* dest_ptr = dest_base + index * primitive_size; char* const dest_end = dest_base + // This handles the case where minor_loop_size does not evenly divide // the most minor dimension. std::min(index + stride_config.minor_loop_size, num_elements) * primitive_size; while (dest_ptr < dest_end) { populator(dest_ptr, minor_scan_indexes, thread_id); ++minor_scan_indexes[stride_config.minor_dimension]; dest_ptr += primitive_size; } return true; }; if (parallel) { ShapeUtil::ForEachIndexParallel(this_shape, stride_config.base, stride_config.dimensions, stride_config.step, init_function); } else { ShapeUtil::ForEachIndex( this_shape, stride_config.base, stride_config.dimensions, stride_config.step, [&init_function]( absl::Span<const int64_t> indexes) -> absl::StatusOr<bool> { auto result_ignored = init_function(indexes, /*thread_id=*/-1); return true; }); } } else { // For scalars. populator(dest_base, {}, /*thread_id=*/-1); } } auto init_function = [&](absl::Span<const int64_t> indexes, int thread_id) -> absl::StatusOr<bool> { const int64_t index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), indexes); DimensionVector minor_scan_indexes(rank, 0); std::copy(indexes.begin(), indexes.end(), minor_scan_indexes.begin()); char* dest_ptr = dest_base + index * primitive_size; char* const dest_end = dest_base + // This handles the case where minor_loop_size does not evenly divide // the most minor dimension. std::min(index + stride_config.minor_loop_size, num_elements) * primitive_size; while (dest_ptr < dest_end) { populator(dest_ptr, minor_scan_indexes, thread_id); ++minor_scan_indexes[stride_config.minor_dimension]; dest_ptr += primitive_size; } return true; }; [&init_function]( absl::Span<const int64_t> indexes) -> absl::StatusOr<bool> { auto result_ignored = init_function(indexes, /*thread_id=*/-1); return true; }); absl::Status MutableLiteralBase::PopulateInplace( absl::FunctionRef<void(void*, absl::Span<const int64_t>)> populator) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); PopulateInplaceInternal( [&](void* dest, absl::Span<const int64_t> indexes, int /*thread_id*/) { return populator(dest, indexes); }, /*parallel=*/false); return absl::OkStatus(); } absl::Status MutableLiteralBase::PopulateInplaceParallel( absl::FunctionRef<void(void*, absl::Span<const int64_t>, int)> populator) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); PopulateInplaceInternal(populator, /*parallel=*/element_count() > 32); return absl::OkStatus(); } Literal LiteralBase::Relayout(const Layout& new_layout, const ShapeIndex& shape_index) const { // Create new shape with 'new_layout' set at the given shape index. Shape new_shape = shape(); Shape* subshape = ShapeUtil::GetMutableSubshape(&new_shape, shape_index); TF_CHECK_OK(LayoutUtil::ValidateLayoutForShape(new_layout, *subshape)); *subshape->mutable_layout() = new_layout; // LINT.IfChange // s4 literals are stored in uint8_t/int8_t, therefore element_size_in_bits // must be removed. if (subshape->layout().element_size_in_bits() == 4) { subshape->mutable_layout()->set_element_size_in_bits(0); } // LINT.ThenChange(//tensorflow/compiler/xla/types.h) Literal result(new_shape); TF_CHECK_OK(result.CopyFrom(*this)); return result; } Literal LiteralBase::Relayout(const Shape& shape_with_layout) const { CHECK(ShapeUtil::Compatible(shape_with_layout, shape())) << "Given shape_with_layout " << ShapeUtil::HumanString(shape_with_layout) << " not compatible with literal shape " << ShapeUtil::HumanString(shape()); Literal result = CreateFromShape(shape_with_layout); ShapeUtil::ForEachSubshape( result.shape(), [this, &result](const Shape& subshape, const ShapeIndex& index) { if (subshape.IsArray()) { TF_CHECK_OK(result.CopyFrom(*this, /*dest_shape_index=*/index, /*src_shape_index=*/index)); } }); return result; } [this, &result](const Shape& subshape, const ShapeIndex& index) { if (subshape.IsArray()) { TF_CHECK_OK(result.CopyFrom(*this, /*dest_shape_index=*/index, /*src_shape_index=*/index)); } }); Literal LiteralBase::ToBoundedDynamic(const Shape& bounded_shape) const { CHECK(bounded_shape.is_dynamic()); Literal result(bounded_shape); ShapeUtil::ForEachSubshape( shape(), [&](const Shape& subshape, const ShapeIndex& index) { if (!subshape.IsArray()) { return; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (bounded_shape.is_dynamic_dimension(i)) { result.SetDynamicSize(i, subshape.dimensions(i)); } } }); TF_CHECK_OK(result.CopyFrom(*this, {}, {}, /*only_dynamic_bound=*/true)); return result; } shape(), [&](const Shape& subshape, const ShapeIndex& index) { if (!subshape.IsArray()) { return; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (bounded_shape.is_dynamic_dimension(i)) { result.SetDynamicSize(i, subshape.dimensions(i)); } } }); Literal LiteralBase::ToStatic() const { // Create new shape with 'new_layout' set at the given shape index. Shape new_shape = shape(); ShapeUtil::ForEachMutableSubshape( &new_shape, [this](Shape* subshape, const ShapeIndex& index) { if (!subshape->IsArray()) { return; } for (int64_t i = 0; i < subshape->rank(); ++i) { // GetDynamicSize has a 32-bit return type and may truncate static // dimensions, so make sure to skip. if (!subshape->is_dynamic_dimension(i)) continue; subshape->set_dynamic_dimension(i, false); subshape->set_dimensions(i, GetDynamicSize(i, index)); } }); Literal result(new_shape); TF_CHECK_OK(result.CopyFrom(*this, {}, {}, /*only_dynamic_bound=*/true)); return result; } &new_shape, [this](Shape* subshape, const ShapeIndex& index) { if (!subshape->IsArray()) { return; } for (int64_t i = 0; i < subshape->rank(); ++i) { // GetDynamicSize has a 32-bit return type and may truncate static // dimensions, so make sure to skip. if (!subshape->is_dynamic_dimension(i)) continue; subshape->set_dynamic_dimension(i, false); subshape->set_dimensions(i, GetDynamicSize(i, index)); } }); absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { absl::StatusOr<Literal> LiteralBase::Broadcast( const Shape& result_shape, absl::Span<const int64_t> dimensions) const { const LiteralBase& src = *this; const Shape& src_shape = shape(); if (!src_shape.IsArray()) { return InvalidArgument("Broadcast only supports arrays."); } const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(src_shape.element_type()); switch (primitive_size) { case 0: return BroadcastHelper<0>(src, src_shape, result_shape, dimensions); case 1: return BroadcastHelper<1>(src, src_shape, result_shape, dimensions); case 2: return BroadcastHelper<2>(src, src_shape, result_shape, dimensions); case 4: return BroadcastHelper<4>(src, src_shape, result_shape, dimensions); case 8: return BroadcastHelper<8>(src, src_shape, result_shape, dimensions); case 16: return BroadcastHelper<16>(src, src_shape, result_shape, dimensions); default: LOG(FATAL) << "Unhandled primitive size " << primitive_size; return InvalidArgument("Unhandled primitive size"); break; } } absl::StatusOr<Literal> LiteralBase::Reshape( absl::Span<const int64_t> dimensions) const { if (!LayoutUtil::IsDenseArray(shape())) { return InvalidArgument("Reshape is only supported for dense arrays."); } if (shape().is_dynamic()) { // TODO(b/243182930): We should consider supporting dynamic reshape. return Unimplemented("Dynamic reshape is not implemented."); } Literal output; if (!LayoutUtil::IsMonotonicWithDim0Major(shape().layout())) { output = Relayout(LayoutUtil::GetDefaultLayoutForRank(shape().rank())); } else { output = Clone(); } // Because the layout is monotonic, we can simply reuse the same sequence of // values without changing their order. *output.mutable_shape_do_not_use() = ShapeUtil::MakeShape(shape().element_type(), dimensions); int64_t elements_before = ShapeUtil::ElementsIn(shape()); int64_t elements_after = ShapeUtil::ElementsIn(output.shape()); if (elements_before != elements_after) { return InvalidArgument( "Shapes before and after Literal::Reshape have different numbers " "of elements: %s vs %s.", ShapeUtil::HumanString(shape()), ShapeUtil::HumanString(output.shape())); } return std::move(output); } Literal LiteralBase::Transpose(absl::Span<const int64_t> permutation) const { CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); CHECK(shape().rank() == permutation.size() && IsPermutation(permutation)) << "Given permutation is not a permutation of dimension numbers"; // To transpose the array, we just permute the dimensions and layout, and // do a straight memory copy of the raw data set. // This is considerably faster than iterating over every array element using // the EachCell<>() and Set<>() APIs. Shape permuted_shape = ShapeUtil::PermuteDimensions(permutation, shape()); // Replace the layout with one affine to this shape, such that a // transpose operation can be performed by leaving the flat values // representation intact. // For example, consider the shape F32[11,8]{1,0} under a {1,0} permutation. // The shape with affine layout resulting from that operation will be // F32[8,11]{0,1}, since it leaves the original most minor (the 8 sized), the // most minor. // // Essentially, given MinMaj(Di) the position of the Di dimension within the // minor to major vector, and given T(Di) the index that the original Di // dimension has within the transposed array, a layout is affine if // MinMaj(Di) == TMinMaj(T(Di)), with TMinMaj() being the minor to major // vector of the affine layout. std::vector<int64_t> inverse_permutation = InversePermutation(permutation); CHECK(LayoutUtil::IsDenseArray(permuted_shape)); Layout* layout = permuted_shape.mutable_layout(); layout->clear_minor_to_major(); for (auto index : LayoutUtil::MinorToMajor(shape())) { layout->add_minor_to_major(inverse_permutation[index]); } Literal new_literal(permuted_shape); if (shape().is_dynamic()) { for (int64_t i = 0; i < shape().rank(); i++) { if (shape().is_dynamic_dimension(i)) { // Set the dynamic size of any dynamic dimension in the transposed // literal. new_literal.SetDynamicSize(inverse_permutation[i], GetDynamicSize(i)); } } } DCHECK_EQ(ShapeUtil::ByteSizeOf(new_literal.shape()), ShapeUtil::ByteSizeOf(shape())); std::memcpy(new_literal.untyped_data(), untyped_data(), size_bytes()); return new_literal; } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( Literal LiteralBase::Slice(absl::Span<const int64_t> start_indices, absl::Span<const int64_t> limit_indices) const { CHECK(shape().IsArray()) << "tuple is not supported for slice"; DimensionVector result_dimensions; for (int64_t dnum = 0; dnum < shape().rank(); ++dnum) { CHECK_GE(start_indices[dnum], 0); CHECK_LE(limit_indices[dnum], shape().dimensions(dnum)) << "dnum = " << dnum; int64_t dimension = limit_indices[dnum] - start_indices[dnum]; CHECK_GE(dimension, 0) << "dnum = " << dnum; result_dimensions.push_back(dimension); } auto result_shape = ShapeUtil::MakeShapeWithDenseLayout( shape().element_type(), result_dimensions, LayoutUtil::MinorToMajor(shape())); ShapeUtil::CopyDynamicDimensions(&result_shape, shape()); Literal result_literal(result_shape); primitive_util::ArrayTypeSwitch<void>( [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; return SliceInternal<NativeT>(*this, start_indices, result_literal); }, result_shape.element_type()); return result_literal; } Literal LiteralBase::Clone() const { Literal result(shape()); TF_CHECK_OK(result.CopyFrom(*this)); return result; } std::unique_ptr<Literal> LiteralBase::CloneToUnique() const { auto result = std::make_unique<Literal>(shape()); TF_CHECK_OK(result->CopyFrom(*this)); return result; } bool LiteralBase::IsDetermined(const ShapeIndex& shape_index) const { return piece(shape_index).IsDetermined(); } bool LiteralBase::IsKnown(const ShapeIndex& shape_index) const { return piece(shape_index).IsKnown(); } std::string LiteralBase::GetAsString(absl::Span<const int64_t> multi_index, const ShapeIndex& shape_index) const { const Shape& subshape = ShapeUtil::GetSubshape(shape(), shape_index); CHECK(LayoutUtil::IsDenseArray(subshape)); return primitive_util::ArrayTypeSwitch<std::string>( [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, subshape.element_type()); } [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, std::optional<int64_t> LiteralBase::GetIntegralAsS64( absl::Span<const int64_t> multi_index) const { CHECK(LayoutUtil::IsDenseArray(shape())); return primitive_util::PrimitiveTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, std::optional<double> LiteralBase::GetAsDouble( absl::Span<const int64_t> multi_index) const { const Shape& s = shape(); CHECK(LayoutUtil::IsDenseArray(s)); return primitive_util::PrimitiveTypeSwitch<std::optional<double>>( [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, s.element_type()); } [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, std::optional<double> LiteralBase::GetSumAsDouble( absl::Span<const int64_t> linear_indices) const { const Shape& s = shape(); CHECK(LayoutUtil::IsDenseArray(s)); if (!primitive_util::IsFloatingPointType(s.element_type())) { return std::nullopt; } return primitive_util::FloatingPointTypeSwitch<double>( [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, s.element_type()); } [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, std::optional<complex128> LiteralBase::GetAsComplex128( absl::Span<const int64_t> multi_index) const { return primitive_util::PrimitiveTypeSwitch<std::optional<complex128>>( [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, absl::Status MutableLiteralBase::SetIntegralAsS64( absl::Span<const int64_t> multi_index, int64_t value) { CHECK(LayoutUtil::IsDenseArray(shape())); return primitive_util::PrimitiveTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, absl::Status MutableLiteralBase::SetFromDouble( absl::Span<const int64_t> multi_index, double value) { CHECK(LayoutUtil::IsDenseArray(shape())); if (!primitive_util::IsFloatingPointType(shape().element_type())) { return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); } primitive_util::FloatingPointTypeSwitch<void>( [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, shape().element_type()); return absl::OkStatus(); } [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, void PrintShape(bool print_layout, const Shape& shape, Printer* printer) { if (print_layout) { ShapeUtil::PrintHumanStringWithLayout(printer, shape); } else { ShapeUtil::PrintHumanString(printer, shape); } } void TuplePrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); printer->Append(oneline ? "( " : "(\n"); for (int i = 0; i < ShapeUtil::TupleElementCount(subshape); ++i) { ShapeIndex element_index = shape_index; element_index.push_back(i); if (i > 0) printer->Append(oneline ? ", " : ",\n"); PrintHelper(literal, element_index, print_shape, print_layout, oneline, printer); } printer->Append(oneline ? " )" : "\n)"); } void DenseArrayPrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); int64_t rank = subshape.rank(); const absl::string_view linebreak = oneline ? " " : "\n"; std::function<void(absl::Span<const int64_t> dimensions, std::vector<int64_t>*)> print_recursive = [&](absl::Span<const int64_t> dimensions, std::vector<int64_t>* accum_indices) { // dimensions.size() decreases by 1 at each recursive call, // and accum_indices->size() increases by 1. // Their sum is equal to the rank of the tensor. CHECK_EQ(rank, dimensions.size() + accum_indices->size()); auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; if (dimensions.empty()) { // Display predicates as 0s and 1s so that the string is more dense. std::string elem; if (subshape.element_type() == PRED && rank > 0) { elem = literal.Get<bool>(*accum_indices, shape_index) ? "1" : "0"; } else { elem = literal.GetAsString(*accum_indices, shape_index); } printer->Append(elem); } else { printer->Append(brace_to_string("{")); for (int i = 0; i < dimensions[0]; ++i) { accum_indices->push_back(i); print_recursive(dimensions.subspan(1), accum_indices); accum_indices->pop_back(); if (i < dimensions[0] - 1) { printer->Append(","); printer->Append(dimensions.size() > 1 ? linebreak : " "); } } printer->Append(brace_to_string("}")); } }; if (print_shape) { PrintShape(print_layout, subshape, printer); if (subshape.is_dynamic()) { printer->Append("("); for (int64_t i = 0; i < subshape.dimensions_size(); ++i) { printer->Append(literal.GetDynamicSize(i, shape_index)); if (i < subshape.dimensions_size() - 1) { printer->Append(","); } } printer->Append(")"); } printer->Append(" "); } std::vector<int64_t> indices = {}; std::vector<int64_t> dimensions; dimensions.reserve(subshape.rank()); for (int64_t i = 0; i < subshape.rank(); ++i) { dimensions.push_back(literal.GetDynamicSize(i, shape_index)); } print_recursive(dimensions, &indices); } print_recursive = [&](absl::Span<const int64_t> dimensions, std::vector<int64_t>* accum_indices) { // dimensions.size() decreases by 1 at each recursive call, // and accum_indices->size() increases by 1. // Their sum is equal to the rank of the tensor. CHECK_EQ(rank, dimensions.size() + accum_indices->size()); auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; if (dimensions.empty()) { // Display predicates as 0s and 1s so that the string is more dense. std::string elem; if (subshape.element_type() == PRED && rank > 0) { elem = literal.Get<bool>(*accum_indices, shape_index) ? "1" : "0"; } else { elem = literal.GetAsString(*accum_indices, shape_index); } printer->Append(elem); } else { printer->Append(brace_to_string("{")); for (int i = 0; i < dimensions[0]; ++i) { accum_indices->push_back(i); print_recursive(dimensions.subspan(1), accum_indices); accum_indices->pop_back(); if (i < dimensions[0] - 1) { printer->Append(","); printer->Append(dimensions.size() > 1 ? linebreak : " "); } } printer->Append(brace_to_string("}")); } }; auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; void PrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); CHECK(LayoutUtil::HasLayout(literal.shape())); CHECK(LayoutUtil::HasLayout(subshape)); if (subshape.IsTuple()) { TuplePrintHelper(literal, shape_index, print_shape, print_layout, oneline, printer); } else if (subshape.IsToken()) { printer->Append("token"); } else { CHECK(LayoutUtil::IsDenseArray(subshape)); if (literal.IsKnown(shape_index)) { DenseArrayPrintHelper(literal, shape_index, print_shape, print_layout, oneline, printer); } else { PrintShape(print_layout, subshape, printer); printer->Append(" "); if (literal.IsDetermined(shape_index)) { printer->Append("unknown"); } else { printer->Append("undetermined"); } } } } void LiteralBase::Print(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/false, /*oneline=*/false, printer); } void LiteralBase::PrintOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/false, /*oneline=*/true, printer); } void LiteralBase::PrintWithoutShape(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/false, /*print_layout=*/false, /*oneline=*/false, printer); } void LiteralBase::PrintWithoutShapeOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/false, /*print_layout=*/false, /*oneline=*/true, printer); } void LiteralBase::PrintWithLayout(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/true, /*oneline=*/false, printer); } void LiteralBase::PrintWithLayoutOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/true, /*oneline=*/true, printer); } std::string LiteralBase::ToString() const { StringPrinter printer; Print(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringOneline() const { StringPrinter printer; PrintOneline(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithoutShape() const { StringPrinter printer; PrintWithoutShape(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithoutShapeOneline() const { StringPrinter printer; PrintWithoutShapeOneline(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithLayout() const { StringPrinter printer; PrintWithLayout(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithLayoutOneline() const { StringPrinter printer; PrintWithLayoutOneline(&printer); return std::move(printer).ToString(); } void LiteralBase::EachCellAsString( absl::FunctionRef<void(absl::Span<const int64_t> indices, const std::string& value)> per_cell) const { if (ShapeUtil::IsZeroElementArray(shape())) { return; } auto indices = IndexUtil::LinearIndexToMultidimensionalIndex( shape(), /*linear_index=*/0); do { per_cell(indices, GetAsString(indices)); } while (IndexUtil::BumpIndices(shape(), absl::MakeSpan(indices))); } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { absl::StatusOr<Literal> ConvertSwitch(const LiteralBase& literal, PrimitiveType primitive_dest_type) { TF_RET_CHECK(LayoutUtil::IsDenseArray(literal.shape())); if (literal.shape().element_type() == primitive_dest_type) { return literal.Clone(); } // Source Array type requirement is ensured by IsDenseArray before. if (!primitive_util::IsArrayType(primitive_dest_type) || !primitive_util::IsArrayType(literal.shape().element_type())) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(literal.shape().element_type()), PrimitiveType_Name(primitive_dest_type)); } // At this point, we know both src & dst are array types, while src is not // complex type, so we can allocate the result literal here to avoid // duplicating it N^2 times in the conversion implementation. Literal result( ShapeUtil::ChangeElementType(literal.shape(), primitive_dest_type)); TF_RETURN_IF_ERROR(primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { return ConvertIfDestTypeMatches<primitive_type_constant>(literal, result); }, literal.shape().element_type())); return result; } absl::StatusOr<Literal> LiteralBase::Convert( PrimitiveType primitive_dest_type) const { return ConvertSwitch(*this, primitive_dest_type); } absl::StatusOr<Literal> LiteralBase::BitcastConvert( const Shape& dest_shape) const { if (ShapeUtil::ByteSizeOf(dest_shape) != ShapeUtil::ByteSizeOf(shape())) { return InvalidArgument( "Can not bitcast-convert from shape %s to a shape of different size %s", shape().ToString(), dest_shape.ToString()); } if (dest_shape.IsTuple() || shape().IsTuple()) { return InvalidArgument( "bitcast-convert is not valid for tuple shapes %s->%s", shape().ToString(), dest_shape.ToString()); } if (shape().is_dynamic() || dest_shape.is_dynamic()) { return InvalidArgument( "bitcast-convert is not valid for dynamic shape %s->%s", shape().ToString(), dest_shape.ToString()); } Literal out(dest_shape); std::memcpy(out.root_piece_.buffer(), root_piece().buffer(), root_piece().size_bytes_dense()); // Perform the reshape on little endian encoding even on big endian machines. if constexpr (!kLittleEndian) { // Swap byte ordering as per the input data type. size_t input_elem_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); TF_RETURN_IF_ERROR(tsl::ByteSwapArray( const_cast<char*>(out.root_piece().buffer()), input_elem_size, out.root_piece().size_bytes_dense() / input_elem_size)); // Swap byte ordering as per the output data type. size_t output_elem_size = ShapeUtil::ByteSizeOfPrimitiveType(dest_shape.element_type()); TF_RETURN_IF_ERROR(tsl::ByteSwapArray( const_cast<char*>(out.root_piece().buffer()), output_elem_size, out.root_piece().size_bytes_dense() / output_elem_size)); } return out; } absl::StatusOr<Literal> LiteralBase::ConvertToShape( const Shape& dest_shape) const { if (!dest_shape.IsTuple()) { return Convert(dest_shape.element_type()); } std::vector<Literal> elements; const auto tuple_element_count = ShapeUtil::TupleElementCount(shape()); elements.reserve(tuple_element_count); for (int i = 0; i < tuple_element_count; ++i) { auto element = LiteralSlice(*this, {i}); TF_ASSIGN_OR_RETURN( auto new_element, element.ConvertToShape(ShapeUtil::GetSubshape(dest_shape, {i}))); elements.push_back(std::move(new_element)); } return MutableLiteralBase::MoveIntoTuple(absl::MakeSpan(elements)); } /* static */ Literal MutableLiteralBase::MoveIntoTuple( absl::Span<Literal> elements) { std::vector<const Shape*> element_shapes; element_shapes.reserve(elements.size()); for (const Literal& element : elements) { element_shapes.push_back(&element.shape()); } Literal literal(ShapeUtil::MakeTupleShapeWithPtrs(element_shapes), /*allocate_arrays=*/false); for (int i = 0, end = elements.size(); i < end; ++i) { TF_CHECK_OK( literal.MoveFrom(std::move(elements[i]), /*dest_shape_index=*/{i})); } return literal; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualDynamicSize( const LiteralBase::Piece& other) const { DCHECK(ShapeUtil::Compatible(subshape(), other.subshape())); if (subshape().is_static()) { return true; } for (int64_t i = 0; i < subshape().rank(); ++i) { if (GetDynamicSize(i) != other.GetDynamicSize(i)) { return false; } } return true; } bool LiteralBase::Piece::EqualElements(const LiteralBase::Piece& other) const { if (subshape().is_static() && ShapeUtil::Equal(subshape(), other.subshape()) && subshape().IsArray()) { CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(size_bytes_dense(), other.size_bytes_dense()); if (primitive_util::IsSubByteNonPredType(subshape().element_type())) { CHECK(!primitive_util::IsFloatingPointType(subshape().element_type())); auto one_array = buffer(); auto two_array = other.buffer(); const int bits_per_element = primitive_util::BitWidth(subshape().element_type()); const uint8_t mask = LsbMask<uint8_t>(bits_per_element); for (int64_t i = 0; i < size_bytes_dense(); ++i) { if ((one_array[i] & mask) != (two_array[i] & mask)) return false; } return true; } return memcmp(buffer(), other.buffer(), size_bytes_dense()) == 0; } std::vector<int64_t> multi_index; return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeSrcT = NativeTypeOf<primitive_type_constant>; return EqualElementsInternal<NativeSrcT>(other, &multi_index); }, subshape().element_type()); } bool LiteralBase::Equal(const LiteralBase& other, bool layout_sensitive) const { // Checking the structure of tuple literals. Checks for dense arrays are // performed below. if (!ShapeUtil::EqualStructure(shape(), other.shape())) { return false; } return root_piece().ForEachSubpieceWithBool([&](const ShapeIndex& index, const Piece& piece) { const Piece& other_piece = other.piece(index); const Shape& subshape = piece.subshape(); const Shape& other_subshape = other_piece.subshape(); if (subshape.element_type() != other_subshape.element_type()) { return false; } if (!piece.subshape().IsArray()) { return true; } if (subshape.rank() != other_subshape.rank()) { return false; } if (layout_sensitive && (subshape.layout() != other_subshape.layout())) { return false; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (piece.GetDynamicSize(i) != other_piece.GetDynamicSize(i)) { return false; } } if (!piece.EqualElements(other_piece)) { return false; } return true; }); } return root_piece().ForEachSubpieceWithBool([&](const ShapeIndex& index, const Piece& piece) { const Piece& other_piece = other.piece(index); const Shape& subshape = piece.subshape(); const Shape& other_subshape = other_piece.subshape(); if (subshape.element_type() != other_subshape.element_type()) { return false; } if (!piece.subshape().IsArray()) { return true; } if (subshape.rank() != other_subshape.rank()) { return false; } if (layout_sensitive && (subshape.layout() != other_subshape.layout())) { return false; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (piece.GetDynamicSize(i) != other_piece.GetDynamicSize(i)) { return false; } } if (!piece.EqualElements(other_piece)) { return false; } return true; }); static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(std::complex<T> a, std::complex<T> b) { return EqualIncludingNan(a.real(), b.real()) && EqualIncludingNan(a.imag(), b.imag()); } static bool EqualIncludingNan(std::complex<T> a, std::complex<T> b) { return EqualIncludingNan(a.real(), b.real()) && EqualIncludingNan(a.imag(), b.imag()); } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } bool Literal::Piece::IsAll(const Literal& scalar) const { CHECK(ShapeUtil::IsScalar(scalar.shape())) << scalar.shape().ToString(); if (!subshape().IsArray()) { return false; } CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(subshape().element_type(), scalar.shape().element_type()); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, subshape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, int64_t Literal::Piece::CountAll(const Literal& scalar) const { CHECK(ShapeUtil::IsScalar(scalar.shape())) << scalar.shape().ToString(); if (!subshape().IsArray()) { return 0; } CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(subshape().element_type(), scalar.shape().element_type()); return primitive_util::ArrayTypeSwitch<int64_t>( [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, subshape().element_type()); } [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { bool LiteralBase::IsAll(const Literal& scalar) const { return root_piece().IsAll(scalar); } bool LiteralBase::IsAll(int8_t value) const { if (!shape().IsArray()) { return false; } PrimitiveType ty = shape().element_type(); if (primitive_util::IsFloatingPointType(ty)) { return IsAllFloatImpl(value, /*round_value=*/false); } if (primitive_util::IsUnsignedIntegralType(ty) && value < 0) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllFloat(float value) const { return IsAllFloatImpl(value, /*round_value=*/true); } bool LiteralBase::IsAllFloatImpl(float value, bool round_value) const { PrimitiveType ty = shape().element_type(); if (!primitive_util::IsFloatingPointType(ty)) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::FloatingPointTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllComplex(complex64 value) const { PrimitiveType ty = shape().element_type(); if (!primitive_util::IsComplexType(ty)) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::ComplexTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllFirst() const { if (!shape().IsArray()) { return false; } // Empty shapes are not all the first element since there is no first element. if (ShapeUtil::IsZeroElementArray(shape())) { return false; } absl::InlinedVector<int64_t, 4> start_indices(/*n=*/shape().rank(), 0); absl::InlinedVector<int64_t, 4> end_indices(/*n=*/shape().rank(), 1); Literal first = Slice(start_indices, end_indices); return IsAll(first.Reshape({}).value()); } bool LiteralBase::IsR1Iota() const { if (!shape().IsArray()) { return false; } CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); if (shape().rank() != 1) { return false; } return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, shape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, std::optional<int64_t> LiteralBase::IsR1StridedIota() const { if (!shape().IsArray() || shape().rank() != 1) { return std::nullopt; } CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); const int64_t elements = ShapeUtil::ElementsIn(shape()); const PrimitiveType type = shape().element_type(); if (elements <= 1 || !primitive_util::IsIntegralType(type)) { return std::nullopt; } return primitive_util::IntegralTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, bool LiteralBase::IsZero(absl::Span<const int64_t> indices) const { CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, shape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void LiteralBase::Piece::set_array_value_state(ArrayValueState state) { array_value_state_ = state; } LiteralBase::ArrayValueState LiteralBase::Piece::get_array_value_state() const { return array_value_state_; } void LiteralBase::Piece::WriteToProto(LiteralProto* proto) const { *proto->mutable_shape() = subshape().ToProto(); switch (subshape().element_type()) { case PRED: CopyToRepeatedField(proto->mutable_preds(), data<bool>()); break; case U2: *proto->mutable_u2s() = std::string( reinterpret_cast<const char*>(data<u2>().data()), size_bytes_dense()); break; case U4: *proto->mutable_u4s() = std::string( reinterpret_cast<const char*>(data<u4>().data()), size_bytes_dense()); break; case U8: proto->set_u8s(static_cast<const unsigned char*>(data<uint8_t>().data()), element_count()); break; case U16: *proto->mutable_u16s() = std::string(reinterpret_cast<const char*>(data<uint16_t>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_u16s()); } break; case U32: CopyToRepeatedField(proto->mutable_u32s(), data<uint32_t>()); break; case U64: CopyToRepeatedField(proto->mutable_u64s(), data<uint64_t>()); break; case S2: *proto->mutable_s2s() = std::string( reinterpret_cast<const char*>(data<s2>().data()), size_bytes_dense()); break; case S4: *proto->mutable_s4s() = std::string( reinterpret_cast<const char*>(data<s4>().data()), size_bytes_dense()); break; case S8: proto->set_s8s(static_cast<const signed char*>(data<int8_t>().data()), element_count()); break; case S16: *proto->mutable_s16s() = std::string(reinterpret_cast<const char*>(data<int16_t>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_s16s()); } break; case S32: CopyToRepeatedField(proto->mutable_s32s(), data<int32_t>()); break; case S64: CopyToRepeatedField(proto->mutable_s64s(), data<int64_t>()); break; case F8E5M2: *proto->mutable_f8e5m2s() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e5m2>().data()), size_bytes_dense()); break; case F8E4M3FN: *proto->mutable_f8e4m3fns() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3fn>().data()), size_bytes_dense()); break; case F8E4M3B11FNUZ: *proto->mutable_f8e4m3b11fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3b11fnuz>().data()), size_bytes_dense()); break; case F8E5M2FNUZ: *proto->mutable_f8e5m2fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e5m2fnuz>().data()), size_bytes_dense()); break; case F8E4M3FNUZ: *proto->mutable_f8e4m3fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3fnuz>().data()), size_bytes_dense()); break; case F16: *proto->mutable_f16s() = std::string(reinterpret_cast<const char*>(data<half>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_f16s()); } break; case BF16: *proto->mutable_bf16s() = std::string(reinterpret_cast<const char*>(data<bfloat16>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_bf16s()); } break; case F32: CopyToRepeatedField(proto->mutable_f32s(), data<float>()); break; case F64: CopyToRepeatedField(proto->mutable_f64s(), data<double>()); break; case C64: for (complex64 value : data<complex64>()) { proto->add_c64s(value.real()); proto->add_c64s(value.imag()); } break; case C128: for (complex128 value : data<complex128>()) { proto->add_c128s(value.real()); proto->add_c128s(value.imag()); } break; case TUPLE: case TOKEN: // Nothing to do but assign the shape which is done above. return; default: // TODO(b/111551621): Support serializing more PrimitiveTypes. LOG(FATAL) << "Unhandled primitive type " << PrimitiveType_Name(subshape().element_type()); } } const void* LiteralBase::Piece::untyped_data() const { DCHECK(LayoutUtil::IsDenseArray(subshape())) << ShapeUtil::HumanString(subshape()); return buffer(); } void* LiteralBase::Piece::untyped_data() { DCHECK(LayoutUtil::IsDenseArray(subshape())) << ShapeUtil::HumanString(subshape()); return buffer(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status LiteralBase::Piece::CopyFromProto(const LiteralProto& proto) { // These conditions should have been checked in // MutableLiteralBase::CreateFromProto. TF_RET_CHECK(proto.has_shape()); Shape shape(proto.shape()); TF_RET_CHECK(LayoutUtil::HasLayout(shape)); TF_RET_CHECK(ShapeUtil::Equal(shape, subshape())); switch (subshape().element_type()) { case PRED: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<bool>(), proto.preds())); break; case S2: { const std::string& s(proto.s2s()); TF_RET_CHECK(data<s2>().size() * sizeof(s2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case S4: { const std::string& s(proto.s4s()); TF_RET_CHECK(data<s4>().size() * sizeof(s4) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case S8: { auto s8_data = data<int8_t>(); TF_RET_CHECK(proto.s8s().size() == s8_data.size()); std::copy(proto.s8s().begin(), proto.s8s().end(), s8_data.begin()); break; } case S16: { const std::string& s(proto.s16s()); TF_RET_CHECK(data<int16_t>().size() * sizeof(int16_t) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case S32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<int32_t>(), proto.s32s())); break; case S64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<int64_t>(), proto.s64s())); break; case U2: { const std::string& s(proto.u2s()); TF_RET_CHECK(data<u2>().size() * sizeof(u2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case U4: { const std::string& s(proto.u4s()); TF_RET_CHECK(data<u4>().size() * sizeof(u4) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case U8: { auto u8_data = data<uint8_t>(); TF_RET_CHECK(proto.u8s().size() == u8_data.size()); std::copy(proto.u8s().begin(), proto.u8s().end(), u8_data.begin()); break; } case U16: { const std::string& s(proto.u16s()); TF_RET_CHECK(data<uint16_t>().size() * sizeof(uint16_t) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case U32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<uint32_t>(), proto.u32s())); break; case U64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<uint64_t>(), proto.u64s())); break; case F8E5M2: { const std::string& s(proto.f8e5m2s()); TF_RET_CHECK(data<tsl::float8_e5m2>().size() * sizeof(tsl::float8_e5m2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3FN: { const std::string& s(proto.f8e4m3fns()); TF_RET_CHECK(data<tsl::float8_e4m3fn>().size() * sizeof(tsl::float8_e4m3fn) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3B11FNUZ: { const std::string& s(proto.f8e4m3b11fnuzs()); TF_RET_CHECK(data<tsl::float8_e4m3b11fnuz>().size() * sizeof(tsl::float8_e4m3b11fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E5M2FNUZ: { const std::string& s(proto.f8e5m2fnuzs()); TF_RET_CHECK(data<tsl::float8_e5m2fnuz>().size() * sizeof(tsl::float8_e5m2fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3FNUZ: { const std::string& s(proto.f8e4m3fnuzs()); TF_RET_CHECK(data<tsl::float8_e4m3fnuz>().size() * sizeof(tsl::float8_e4m3fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F16: { const std::string& s(proto.f16s()); TF_RET_CHECK(data<half>().size() * sizeof(half) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case BF16: { const std::string& s(proto.bf16s()); TF_RET_CHECK(data<bfloat16>().size() * sizeof(bfloat16) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case F32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<float>(), proto.f32s())); break; case F64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<double>(), proto.f64s())); break; case C64: { auto complex_data = data<complex64>(); TF_RET_CHECK(proto.c64s_size() == complex_data.size() * 2); for (int64_t i = 0; i < complex_data.size(); ++i) { complex_data[i] = complex64{proto.c64s(i * 2), proto.c64s(i * 2 + 1)}; } break; } case C128: { auto complex_data = data<complex128>(); const int64_t complex_data_size_doubled = complex_data.size() * 2; TF_RET_CHECK(proto.c128s_size() == complex_data_size_doubled); for (int64_t i = 0, end = complex_data.size(); i < end; ++i) { complex_data[i] = complex128{proto.c128s(i * 2), proto.c128s(i * 2 + 1)}; } break; } case TUPLE: return InvalidArgument("Should not be called on tuple shapes: %s", ShapeUtil::HumanString(subshape())); default: return InvalidArgument("Is called on unsupported shape: %s", ShapeUtil::HumanString(subshape())); } return absl::OkStatus(); } bool LiteralBase::Piece::IsKnown() const { if (array_value_state_ != ArrayValueState::kKnown) { return false; } if (subshape().IsTuple()) { bool are_all_leaf_arrays_known = true; ForEachSubpiece([&are_all_leaf_arrays_known](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_known &= piece.IsKnown(); }); return are_all_leaf_arrays_known; } return true; } ForEachSubpiece([&are_all_leaf_arrays_known](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_known &= piece.IsKnown(); }); bool LiteralBase::Piece::IsDetermined() const { if (array_value_state_ == ArrayValueState::kUndetermined) { return false; } if (subshape().IsTuple()) { bool are_all_leaf_arrays_determined = true; ForEachSubpiece([&are_all_leaf_arrays_determined](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_determined &= piece.IsDetermined(); }); return are_all_leaf_arrays_determined; } return true; } ForEachSubpiece([&are_all_leaf_arrays_determined](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_determined &= piece.IsDetermined(); }); LiteralProto LiteralBase::ToProto() const { LiteralProto proto; root_piece().ForEachSubpiece( [&](const ShapeIndex& index, const Piece& piece) { LiteralProto* proto_piece = &proto; for (int64_t i : index) { while (proto_piece->tuple_literals_size() <= i) { proto_piece->add_tuple_literals(); } proto_piece = proto_piece->mutable_tuple_literals(i); } piece.WriteToProto(proto_piece); }); return proto; } [&](const ShapeIndex& index, const Piece& piece) { LiteralProto* proto_piece = &proto; for (int64_t i : index) { while (proto_piece->tuple_literals_size() <= i) { proto_piece->add_tuple_literals(); } proto_piece = proto_piece->mutable_tuple_literals(i); } piece.WriteToProto(proto_piece); }); const void* LiteralBase::untyped_data(const ShapeIndex& shape_index) const { return piece(shape_index).untyped_data(); } void* MutableLiteralBase::untyped_data(const ShapeIndex& shape_index) { return piece(shape_index).untyped_data(); } int64_t LiteralBase::size_bytes(const ShapeIndex& shape_index) const { return piece(shape_index).size_bytes_dense(); } std::string LiteralBase::GetR1U8AsString() const { CHECK(shape().IsArray()); CHECK_EQ(shape().rank(), 1); CHECK_EQ(shape().element_type(), U8); return std::string(absl::bit_cast<const char*>(data<uint8_t>().data()), ShapeUtil::ElementsIn(shape())); } void MutableBorrowingLiteral::CopyPieceSubtree(const Shape& shape, const Piece* src_piece, Piece* dest_piece) { DCHECK(ShapeUtil::Equal(src_piece->subshape(), dest_piece->subshape())) << "src_piece has shape: " << ShapeUtil::HumanString(src_piece->subshape()) << "dest_piece has shape: " << ShapeUtil::HumanString(dest_piece->subshape()); dest_piece->set_array_value_state(src_piece->get_array_value_state()); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); Piece child_piece; child_piece.set_subshape(&subshape); CopyPieceSubtree(subshape, &src_piece->child(i), &child_piece); dest_piece->emplace_back(std::move(child_piece)); } } else if (shape.IsArray()) { dest_piece->set_buffer(const_cast<char*>(src_piece->buffer())); } } MutableLiteralBase::~MutableLiteralBase() = default; MutableBorrowingLiteral::MutableBorrowingLiteral( const MutableBorrowingLiteral& literal) : MutableLiteralBase() { shape_ = literal.shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.root_piece(), root_piece_); } MutableBorrowingLiteral& MutableBorrowingLiteral::operator=( const MutableBorrowingLiteral& literal) { shape_ = literal.shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.root_piece(), root_piece_); return *this; } MutableBorrowingLiteral::MutableBorrowingLiteral(MutableLiteralBase* literal) : MutableLiteralBase() { shape_ = literal->shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal->root_piece(), root_piece_); } MutableBorrowingLiteral::MutableBorrowingLiteral( MutableBorrowingLiteral literal, const ShapeIndex& view_root) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(literal.piece(view_root).subshape()); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.piece(view_root), root_piece_); } MutableBorrowingLiteral::MutableBorrowingLiteral(const char* src_buf_ptr, const Shape& shape) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(shape); CHECK(LayoutUtil::HasLayout(*shape_)); CHECK(!shape_->IsTuple()); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); root_piece_->set_buffer(const_cast<char*>(src_buf_ptr)); } MutableBorrowingLiteral::MutableBorrowingLiteral(absl::Span<char*> src_buf_ptrs, const Shape& shape) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(shape); if (!shape_->IsTuple()) { CHECK_EQ(src_buf_ptrs.size(), 1); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); root_piece_->set_buffer(const_cast<char*>(src_buf_ptrs[0])); } else { CHECK(!ShapeUtil::IsNestedTuple(*shape_)); CHECK_EQ(src_buf_ptrs.size(), ShapeUtil::TupleElementCount(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); for (int i = 0; i < src_buf_ptrs.size(); ++i) { Piece child_piece; const auto& src_shape = shape_->tuple_shapes(i); CHECK(src_shape.IsArray()); child_piece.set_subshape(&src_shape); child_piece.set_buffer(src_buf_ptrs[i]); root_piece_->emplace_back(std::move(child_piece)); } } } MutableBorrowingLiteral::MutableBorrowingLiteral(ShapeTree<char*> src_buf_ptrs) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(src_buf_ptrs.shape()); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); BuildPieceSubtree(*shape_, root_piece_); root_piece_->ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); } [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); MutableBorrowingLiteral::~MutableBorrowingLiteral() { if (root_piece_ != nullptr) { delete root_piece_; } } LiteralSlice::LiteralSlice(const LiteralBase& literal) : LiteralBase(), root_piece_(&literal.root_piece()) {} LiteralSlice::LiteralSlice(const LiteralBase& literal, const ShapeIndex& view_root) : LiteralBase(), root_piece_(&literal.piece(view_root)) {} BorrowingLiteral::BorrowingLiteral(const char* src_buf_ptr, const Shape& shape) : LiteralBase(), shape_(std::make_unique<Shape>(shape)) { CHECK(shape_->IsArray()); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); root_piece_.set_buffer(const_cast<char*>(src_buf_ptr)); } BorrowingLiteral::BorrowingLiteral(absl::Span<const char* const> src_buf_ptrs, const Shape& shape) : LiteralBase(), shape_(std::make_unique<Shape>(shape)) { CHECK(shape_->IsTuple()); CHECK(!ShapeUtil::IsNestedTuple(*shape_)); CHECK_EQ(src_buf_ptrs.size(), ShapeUtil::TupleElementCount(*shape_)); root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); BuildPieceSubtree(*shape_, &root_piece_); for (int i = 0, end = src_buf_ptrs.size(); i < end; ++i) { const auto& src_shape = shape_->tuple_shapes(i); CHECK(src_shape.IsArray()); root_piece_.child(i).set_buffer(const_cast<char*>(src_buf_ptrs[i])); } } BorrowingLiteral::BorrowingLiteral(ShapeTree<const char*> src_buf_ptrs) : LiteralBase(), shape_(std::make_unique<Shape>(src_buf_ptrs.shape())) { root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); BuildPieceSubtree(*shape_, &root_piece_); root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); } [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); });
#include "xla/literal.h" #include <algorithm> #include <cmath> #include <complex> #include <cstdint> #include <functional> #include <limits> #include <random> #include <string> #include <tuple> #include <utility> #include <vector> #include "absl/base/casts.h" #include "absl/hash/hash.h" #include "absl/random/random.h" #include "absl/status/status.h" #include "absl/strings/match.h" #include "absl/types/span.h" #include "xla/array.h" #include "xla/array2d.h" #include "xla/array3d.h" #include "xla/array4d.h" #include "xla/index_util.h" #include "xla/layout.h" #include "xla/layout_util.h" #include "xla/literal_util.h" #include "xla/primitive_util.h" #include "xla/shape.h" #include "xla/shape_tree.h" #include "xla/shape_util.h" #include "xla/test.h" #include "xla/types.h" #include "xla/util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/errors.h" #include "tsl/platform/logging.h" // IWYU pragma: keep #include "tsl/platform/macros.h" #include "tsl/platform/ml_dtypes.h" #include "tsl/platform/statusor.h" #include "tsl/platform/test_benchmark.h" class LiteralUtilTest : public ::testing::Test { protected: LiteralUtilTest() { Array4D<float> arr4d({ // clang-format off { // i0=0 { // i1=0 {1, 2, 3}, // i2=0 {4, 5, 6}, // i2=1 {7, 8, 9}, // i2=2 }, { // i1=1 {11, 12, 13}, {14, 15, 16}, {17, 18, 19}, }, }, { // i0=1 { // i1=0 {101, 102, 103}, {104, 105, 106}, {107, 108, 109}, }, { // i1=1 {201, 202, 203}, // i2=0 {204, 205, 206}, // i2=1 {207, 208, 209}, // i2=2 }, }, // clang-format on }); layout_r2_dim0major_ = LayoutUtil::MakeLayout({1, 0}); layout_r2_dim0minor_ = LayoutUtil::MakeLayout({0, 1}); layout_r3_dim0major_ = LayoutUtil::MakeLayout({2, 1, 0}); layout_r3_dim0minor_ = LayoutUtil::MakeLayout({0, 1, 2}); layout_r4_dim0major_ = LayoutUtil::MakeLayout({3, 2, 1, 0}); layout_r4_dim0minor_ = LayoutUtil::MakeLayout({0, 1, 2, 3}); literal_r4_2x2x3x3_dim0major_ = LiteralUtil::CreateR4FromArray4DWithLayout<float>(arr4d, layout_r4_dim0major_); literal_r4_2x2x3x3_dim0minor_ = LiteralUtil::CreateR4FromArray4DWithLayout<float>(arr4d, layout_r4_dim0minor_); } Layout layout_r2_dim0major_; Layout layout_r2_dim0minor_; Layout layout_r3_dim0major_; Layout layout_r3_dim0minor_; Layout layout_r4_dim0major_; Layout layout_r4_dim0minor_; Literal literal_r4_2x2x3x3_dim0major_; Literal literal_r4_2x2x3x3_dim0minor_; }; TEST_F(LiteralUtilTest, BorrowingLiteralFromMultipleBufferPtrs) { std::vector<int64_t> one_two_three = {1, 2, 3}; const Shape one_two_three_shape = ShapeUtil::MakeShape(S64, {3}); std::vector<int64_t> hundred = {100}; const Shape hundred_shape = ShapeUtil::MakeShape(S64, {1}); std::vector<const char*> src_buf_ptrs; src_buf_ptrs.emplace_back( reinterpret_cast<const char*>(one_two_three.data())); src_buf_ptrs.emplace_back(reinterpret_cast<const char*>(hundred.data())); auto literal_tuple = BorrowingLiteral( src_buf_ptrs, ShapeUtil::MakeTupleShape({one_two_three_shape, hundred_shape})); EXPECT_EQ( literal_tuple.Get<int64_t>(/*multi_index=*/{0}, /*shape_index=*/{0}), 1); EXPECT_EQ( literal_tuple.Get<int64_t>(/*multi_index=*/{0}, /*shape_index=*/{1}), 100); EXPECT_EQ( literal_tuple.Get<int64_t>(/*multi_index=*/{1}, /*shape_index=*/{0}), 2); EXPECT_EQ( literal_tuple.Get<int64_t>(/*multi_index=*/{2}, /*shape_index=*/{0}), 3); }
LiteralUtilTest_BorrowingLiteralFromOneBufferPtr
xla/literal_test.cc
bool LiteralProtoHasValues(const LiteralProto& proto) { return !proto.s2s().empty() || !proto.s4s().empty() || !proto.s8s().empty() || !proto.s16s().empty() || proto.s32s_size() || proto.s64s_size() || !proto.u2s().empty() || !proto.u4s().empty() || !proto.u8s().empty() || !proto.u16s().empty() || proto.u32s_size() || proto.u64s_size() || !proto.f8e5m2s().empty() || !proto.f8e4m3fns().empty() || !proto.f8e4m3b11fnuzs().empty() || !proto.f8e5m2fnuzs().empty() || !proto.f8e4m3fnuzs().empty() || !proto.f16s().empty() || !proto.bf16s().empty() || proto.f32s_size() || proto.f64s_size() || proto.c64s_size() || proto.c128s_size() || proto.preds_size() || proto.tuple_literals_size(); } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { const Shape& NilShape() { static const Shape* shape = new Shape(TUPLE, {}, {}, {}); return *shape; } const Shape* TryInternShape(const Shape& shape) { if (shape.IsTuple() && shape.tuple_shapes_size() == 0) { return &NilShape(); } if (shape.IsArray() && shape.dimensions_size() == 0 && shape.is_static() && shape.layout().tiles_size() == 0 && shape.layout().memory_space() == 0) { return &ScalarShape(shape.element_type()); } return nullptr; } StrideConfig::StrideConfig(const Shape& source_shape, const Shape& dest_shape, absl::Span<const int64_t> dimensions) : dimensions(dimensions), base(dimensions.size(), 0), step(dimensions.size(), 1) { if (!dimensions.empty()) { // Selects the shape with the largest minor dimension as the one upon // which to run the tight stride loop. if (dimensions[LayoutUtil::Minor(source_shape.layout(), 0)] >= dimensions[LayoutUtil::Minor(dest_shape.layout(), 0)]) { minor_dimension = LayoutUtil::Minor(source_shape.layout(), 0); dest_stride = IndexUtil::GetDimensionStride(dest_shape, minor_dimension); } else { minor_dimension = LayoutUtil::Minor(dest_shape.layout(), 0); source_stride = IndexUtil::GetDimensionStride(source_shape, minor_dimension); } minor_loop_size = dimensions[minor_dimension]; step[minor_dimension] = minor_loop_size; } } LiteralBase::~LiteralBase() = default; const Shape& LiteralBase::shape() const { return root_piece().subshape(); } const char* LiteralBase::Piece::buffer() const { // std::visit is avoided here due to its code size issues. if (auto* r = std::get_if<DenseRep>(&rep_)) { return r->data; } if (auto* r = std::get_if<DenseInlinedRep>(&rep_)) { return r->data; } DCHECK(std::holds_alternative<TupleRep>(rep_) || std::holds_alternative<Uninitialized>(rep_)); return nullptr; } const LiteralBase::Piece& LiteralBase::piece( const ShapeIndex& shape_index) const { const Piece* piece = &root_piece(); for (const auto i : shape_index) { DCHECK_GE(i, 0); DCHECK_LT(i, piece->children_size()); piece = &piece->child(i); } return *piece; } std::ostream& operator<<(std::ostream& out, const Literal& literal) { out << literal.ToString(); return out; } Shape* MutableLiteralBase::mutable_shape_do_not_use() { const Shape* const_shape = shape_.get(); if (!shape_.OwnsPtr()) { shape_ = MaybeOwningShapePtr(std::make_unique<Shape>(*shape_)); } Shape* shape = shape_.get_mutable(); if (shape != const_shape) { std::function<void(const Shape&, Piece*)> set_piece_shapes = [&set_piece_shapes](const Shape& shape, Piece* piece) { piece->set_subshape(&shape); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); set_piece_shapes(subshape, &piece->child(i)); } } }; set_piece_shapes(*shape, &mutable_root_piece()); } return shape; } [&set_piece_shapes](const Shape& shape, Piece* piece) { piece->set_subshape(&shape); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); set_piece_shapes(subshape, &piece->child(i)); } } }; Literal::Literal() : Literal(NilShape()) {} Literal::Literal(const Shape& shape) : Literal(shape, /*allocate_arrays=*/true) {} void Literal::SetShape(const Shape& shape) { Shape shape_storage; const Shape* shape_ptr = &shape; if (LayoutUtil::HasCustomElementSizeInBits(shape)) { shape_storage = shape; shape_storage.mutable_layout()->set_element_size_in_bits(0); shape_ptr = &shape_storage; } if (const Shape* intered_shape_ptr = TryInternShape(*shape_ptr)) { shape_ = intered_shape_ptr; } else { shape_ = std::make_unique<Shape>(*shape_ptr); } } void Literal::SetPiece(const Shape& shape, Piece* piece, bool allocate_arrays, ArrayValueState leaf_array_value_state) { if (shape.IsTuple()) { for (const Shape& subshape : shape.tuple_shapes()) { Piece child_piece; child_piece.set_subshape(&subshape); SetPiece(subshape, &child_piece, allocate_arrays, leaf_array_value_state); piece->emplace_back(std::move(child_piece)); } } else if (shape.IsArray()) { DCHECK(LayoutUtil::IsDenseArray(shape)) << "literal array storage is currently only supported for dense " "arrays: " << shape; piece->set_array_value_state(leaf_array_value_state); if (leaf_array_value_state == LiteralBase::ArrayValueState::kKnown && allocate_arrays) { piece->AllocateBuffers(); } } } Literal::Literal(const Shape& shape, bool allocate_arrays, ArrayValueState leaf_array_value_state) : MutableLiteralBase() { SetShape(shape); CHECK(leaf_array_value_state != ArrayValueState::kKnown || LayoutUtil::HasLayout(*shape_)); root_piece_.set_subshape(shape_.get()); CHECK(&root_piece_.subshape() == shape_.get()); SetPiece(*shape_, &root_piece_, allocate_arrays, leaf_array_value_state); } Literal::~Literal() { DeallocateBuffers(); } void Literal::DeallocateBuffers() { root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { piece->DeallocateBuffers(); }); } Literal::Literal(Literal&& other) : MutableLiteralBase() { *this = std::move(other); } Literal& Literal::operator=(Literal&& other) { DCHECK(&other.root_piece_.subshape() == other.shape_.get()); using std::swap; swap(shape_, other.shape_); swap(root_piece_, other.root_piece_); DCHECK(&root_piece_.subshape() == shape_.get()); return *this; } Literal LiteralBase::CreateFromShape(const Shape& shape) { Literal literal(shape); literal.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (piece->subshape().IsArray()) { memset(piece->untyped_data(), 0, piece->size_bytes_dense()); } }); return literal; } [&](const ShapeIndex& index, Piece* piece) { if (piece->subshape().IsArray()) { memset(piece->untyped_data(), 0, piece->size_bytes_dense()); } }); Literal LiteralBase::CreateFromShapeWithUnknownLeafArrays(const Shape& shape) { Literal literal(shape, /*allocate_arrays=*/false, ArrayValueState::kUnknown); return literal; } Literal LiteralBase::CreateFromShapeWithUndeterminedLeafArrays( const Shape& shape) { Literal literal(shape, /*allocate_arrays=*/false, ArrayValueState::kUndetermined); return literal; } int32_t LiteralBase::GetDynamicSize(int64_t dim_index) const { return GetDynamicSize(dim_index, {}); } int32_t LiteralBase::GetDynamicSize(int64_t dim_index, const ShapeIndex& shape_index) const { return piece(shape_index).GetDynamicSize(dim_index); } std::optional<int64_t> LiteralBase::GetFirstInteger() const { if (!primitive_util::IsIntegralType(shape().element_type())) { return std::nullopt; } return primitive_util::IntegralTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, void LiteralBase::BuildPieceSubtree(const Shape& shape, Piece* piece) { CHECK(shape.IsTuple()); for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); Piece child_piece; child_piece.set_subshape(&subshape); if (subshape.IsTuple()) { BuildPieceSubtree(subshape, &child_piece); } piece->emplace_back(std::move(child_piece)); } } absl::Status LiteralBase::SerializeToString(std::string* output) const { ShapeProto shape_proto = shape().ToProto(); TF_ASSIGN_OR_RETURN(int64_t size, ShapeUtil::SerializedSizeWithProto(shape(), shape_proto)); output->resize(size); return SerializeWithShapeProto(shape_proto, output->data()); } absl::StatusOr<std::string> LiteralBase::SerializeAsString() const { std::string result; TF_RETURN_IF_ERROR(SerializeToString(&result)); return std::move(result); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { void MutableLiteralBase::CopyElementFrom(const LiteralSlice& src_literal, absl::Span<const int64_t> src_index, absl::Span<const int64_t> dest_index) { DCHECK(LayoutUtil::IsDenseArray(shape())); DCHECK_EQ(shape().element_type(), src_literal.shape().element_type()); const int64_t src_linear_index = IndexUtil::MultidimensionalIndexToLinearIndex(src_literal.shape(), src_index); const int64_t dest_linear_index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), dest_index); const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); char* dest_address = static_cast<char*>(untyped_data()) + dest_linear_index * primitive_size; const char* source_address = static_cast<const char*>(src_literal.untyped_data()) + src_linear_index * primitive_size; if (dest_address != source_address) { memcpy(dest_address, source_address, primitive_size); } } /* static */ absl::StatusOr<Literal> MutableLiteralBase::CreateFromProto( const LiteralProto& proto, bool prohibit_empty_literal) { if (!proto.has_shape()) { return InvalidArgument("LiteralProto has no shape"); } Shape shape(proto.shape()); if (ShapeUtil::HasPrimitiveType(shape, OPAQUE_TYPE)) { return InvalidArgument( "Literal shape cannot include OPAQUE_TYPE sub-shape"); } if (!LayoutUtil::HasLayout(shape)) { return InvalidArgument("LiteralProto has no layout"); } if (LayoutUtil::IsSparseArray(shape)) { return Unimplemented("Sparse literals are not supported"); } TF_RETURN_IF_ERROR(ShapeUtil::ValidateShapeWithOptionalLayout(shape)); Literal literal(shape); TF_RETURN_IF_ERROR(literal.root_piece_.ForEachMutableSubpieceWithStatus( [&](const ShapeIndex& index, Piece* piece) -> absl::Status { const LiteralProto* proto_element = &proto; for (int64_t i : index) { CHECK(i < proto_element->tuple_literals_size()); proto_element = &proto_element->tuple_literals(i); } if (piece->subshape().IsTuple()) { if (proto_element->tuple_literals_size() != ShapeUtil::TupleElementCount(piece->subshape())) { return InvalidArgument( "Expected %d tuple elements in LiteralProto, has %d", ShapeUtil::TupleElementCount(piece->subshape()), proto_element->tuple_literals_size()); } return absl::OkStatus(); } if (piece->subshape().element_type() == TOKEN) { return absl::OkStatus(); } CHECK(piece->subshape().IsArray()); // When prohibit_empty_literal is false (allowing literal with no // values), only copy from proto if the literal proto has values. This // mode is used for a learned cost model. if (prohibit_empty_literal || LiteralProtoHasValues(*proto_element)) { TF_RETURN_IF_ERROR(piece->CopyFromProto(*proto_element)); } return absl::OkStatus(); })); return std::move(literal); } TF_RETURN_IF_ERROR(literal.root_piece_.ForEachMutableSubpieceWithStatus( Literal Literal::SubLiteral(ShapeIndexView shape_index) { if (!shape_index.empty()) { auto decomposed = this->DecomposeTuple(); return decomposed.at(shape_index.front()) .SubLiteral(shape_index.subspan(1)); } else { return std::move(*this); } } std::vector<Literal> Literal::DecomposeTuple() { CHECK(shape().IsTuple()); std::vector<Literal> elements; const auto tuple_element_count = ShapeUtil::TupleElementCount(shape()); elements.reserve(tuple_element_count); for (int i = 0; i < tuple_element_count; ++i) { elements.push_back(Literal(ShapeUtil::GetSubshape(shape(), {i}), /*allocate_arrays=*/false)); Literal& element = elements.back(); element.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* dest_piece) { if (dest_piece->subshape().IsTuple()) { return; } ShapeIndex src_index = {i}; for (int64_t j : index) { src_index.push_back(j); } Piece& src_piece = piece(src_index); // Move the respective buffer over to the element Literal. dest_piece->MoveDataFrom(src_piece); }); } // Set this literal to be nil-shaped. *this = Literal(); return elements; } [&](const ShapeIndex& index, Piece* dest_piece) { if (dest_piece->subshape().IsTuple()) { return; } ShapeIndex src_index = {i}; for (int64_t j : index) { src_index.push_back(j); } Piece& src_piece = piece(src_index); // Move the respective buffer over to the element Literal. dest_piece->MoveDataFrom(src_piece); }); void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } int32_t LiteralBase::Piece::GetDynamicSize(int64_t dim_index) const { CHECK(LayoutUtil::IsDenseArray(subshape())); if (!subshape_->is_dynamic_dimension(dim_index)) { // This is a static dimension, return size. return subshape_->dimensions(dim_index); } return dynamic_size_buffer()[dim_index]; } void LiteralBase::Piece::SetDynamicSize(int64_t dim_index, int32_t size) { CHECK(LayoutUtil::IsDenseArray(subshape())); CHECK(subshape_->is_dynamic_dimension(dim_index)); dynamic_size_buffer()[dim_index] = size; } void LiteralBase::Piece::AllocateBuffers() { const int64_t bytes = total_bytes_dense(); if (bytes > kMaxInlinedBytes) { CHECK_EQ(buffer(), nullptr); rep_.emplace<DenseRep>(); set_buffer( static_cast<char*>(tsl::port::AlignedMalloc(bytes, kMinimumAlignment))); } else { rep_.emplace<DenseInlinedRep>(); } } void LiteralBase::Piece::DeallocateBuffers() { if (auto* array_rep = GetDenseRep()) { tsl::port::AlignedFree(array_rep->data); rep_.emplace<Uninitialized>(); } } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } absl::Status LiteralBase::Piece::CopyFrom(const LiteralBase::Piece& src, bool only_dynamic_bound) { CHECK(subshape_ != nullptr); CHECK(src.subshape_ != nullptr); CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK(LayoutUtil::IsDenseArray(src.subshape())) << __func__ << " is only supported for dense arrays: " << src.subshape(); if (!only_dynamic_bound) { CHECK(ShapeUtil::Compatible(subshape(), src.subshape())); } if (src.array_value_state_ == ArrayValueState::kUnknown || src.array_value_state_ == ArrayValueState::kUndetermined) { if (array_value_state_ == ArrayValueState::kKnown) { DeallocateBuffers(); } array_value_state_ = src.array_value_state_; return absl::OkStatus(); } else { CHECK(src.array_value_state_ == ArrayValueState::kKnown); if (array_value_state_ == ArrayValueState::kUndetermined || array_value_state_ == ArrayValueState::kUnknown) { AllocateBuffers(); } array_value_state_ = src.array_value_state_; } if (ShapeUtil::Equal(subshape(), src.subshape())) { // If the layouts are equal it's faster just to memcpy. memcpy(buffer(), src.buffer(), src.size_bytes_dense()); } else { std::vector<int64_t> origin(subshape().rank(), 0); primitive_util::ArrayTypeSwitch<void>( [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, subshape().element_type()); } DCHECK_EQ(dynamic_size_buffer_bytes(), src.dynamic_size_buffer_bytes()); if (subshape().is_dynamic() && src.subshape().is_dynamic()) { memcpy(dynamic_size_buffer(), src.dynamic_size_buffer(), src.dynamic_size_buffer_bytes()); } return absl::OkStatus(); } [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, void MutableLiteralBase::SetDynamicSize(int64_t dim_index, int32_t size) { return SetDynamicSize(dim_index, {}, size); } void MutableLiteralBase::SetDynamicSize(int64_t dim_index, const ShapeIndex& shape_index, int32_t size) { Shape* subshape = ShapeUtil::GetMutableSubshape(mutable_shape_do_not_use(), shape_index); CHECK(LayoutUtil::IsDenseArray(*subshape)) << __func__ << " is only supported for dense arrays: " << *subshape; CHECK_GE(subshape->dimensions(dim_index), size); subshape->set_dynamic_dimension(dim_index, true); CHECK_EQ(&piece(shape_index).subshape(), subshape); piece(shape_index).SetDynamicSize(dim_index, size); } absl::Status MutableLiteralBase::CopyFrom(const LiteralSlice& src_literal, const ShapeIndex& dest_shape_index, const ShapeIndex& src_shape_index, bool only_dynamic_bound) { const Shape& dest_subshape = ShapeUtil::GetSubshape(shape(), dest_shape_index); const Shape& src_subshape = ShapeUtil::GetSubshape(src_literal.shape(), src_shape_index); if (only_dynamic_bound) { auto& bound_shape = dest_subshape.is_static() ? src_subshape : dest_subshape; auto& compact_shape = dest_subshape.is_static() ? dest_subshape : src_subshape; CHECK(ShapeUtil::DynamicShapeIsCompatible(compact_shape, bound_shape)) << compact_shape.ToString() << " vs " << bound_shape.ToString(); } else { if (!ShapeUtil::Compatible(dest_subshape, src_subshape)) { return InvalidArgument( "Destination subshape incompatible with source subshape: %s vs %s", ShapeUtil::HumanString(dest_subshape), ShapeUtil::HumanString(src_subshape)); } } return mutable_root_piece().ForEachMutableSubpieceWithStatus( [&](const ShapeIndex& index, Piece* piece) { if (!piece->subshape().IsArray()) { return absl::OkStatus(); } // Determine if this index is in the part of this literal that we want // to copy over from src_literal. bool in_subtree_to_copy = true; for (int i = 0; i < dest_shape_index.size(); ++i) { if (index[i] != dest_shape_index[i]) { in_subtree_to_copy = false; break; } } if (!in_subtree_to_copy) { return absl::OkStatus(); } // Construct the index of the corresponding piece in the source literal. ShapeIndex src_piece_index = src_shape_index; for (int64_t i = dest_shape_index.size(), end = index.size(); i < end; ++i) { src_piece_index.push_back(index[i]); } TF_RETURN_IF_ERROR( piece->CopyFrom(src_literal.piece(src_piece_index), /*only_dynamic_bound=*/only_dynamic_bound)); return absl::OkStatus(); }); } [&](const ShapeIndex& index, Piece* piece) { if (!piece->subshape().IsArray()) { return absl::OkStatus(); } // Determine if this index is in the part of this literal that we want // to copy over from src_literal. bool in_subtree_to_copy = true; for (int i = 0; i < dest_shape_index.size(); ++i) { if (index[i] != dest_shape_index[i]) { in_subtree_to_copy = false; break; } } if (!in_subtree_to_copy) { return absl::OkStatus(); } // Construct the index of the corresponding piece in the source literal. ShapeIndex src_piece_index = src_shape_index; for (int64_t i = dest_shape_index.size(), end = index.size(); i < end; ++i) { src_piece_index.push_back(index[i]); } TF_RETURN_IF_ERROR( piece->CopyFrom(src_literal.piece(src_piece_index), /*only_dynamic_bound=*/only_dynamic_bound)); return absl::OkStatus(); }); absl::Status Literal::MoveFrom(Literal&& src_literal, const ShapeIndex& dest_shape_index) { const Shape& dest_subshape = ShapeUtil::GetSubshape(shape(), dest_shape_index); if (!ShapeUtil::Equal(dest_subshape, src_literal.shape())) { return InvalidArgument( "Destination subshape not equal to source shape: %s vs %s", ShapeUtil::HumanString(dest_subshape), ShapeUtil::HumanString(src_literal.shape())); } src_literal.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& src_index, Piece* src_piece) { if (!src_piece->subshape().IsArray()) { return; } ShapeIndex dest_index = dest_shape_index; for (int64_t i : src_index) { dest_index.push_back(i); } Piece& dest_piece = piece(dest_index); dest_piece.DeallocateBuffers(); dest_piece.MoveDataFrom(*src_piece); }); src_literal.shape_ = MaybeOwningShapePtr(&NilShape()); src_literal.root_piece_ = Piece(); src_literal.root_piece_.set_subshape(src_literal.shape_.get()); return absl::OkStatus(); } [&](const ShapeIndex& src_index, Piece* src_piece) { if (!src_piece->subshape().IsArray()) { return; } ShapeIndex dest_index = dest_shape_index; for (int64_t i : src_index) { dest_index.push_back(i); } Piece& dest_piece = piece(dest_index); dest_piece.DeallocateBuffers(); dest_piece.MoveDataFrom(*src_piece); }); absl::Status MutableLiteralBase::CopySliceFrom( const LiteralSlice& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << shape(); TF_RET_CHECK(LayoutUtil::IsDenseArray(src_literal.shape())) << src_literal.shape(); TF_RET_CHECK(ShapeUtil::SameElementType(src_literal.shape(), shape())); TF_RET_CHECK(src_literal.shape().rank() == src_base.size()); TF_RET_CHECK(shape().rank() == dest_base.size()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, void MutableLiteralBase::PopulateR1(const tsl::core::Bitmap& values) { CHECK(shape().IsArray()); CHECK_EQ(shape().rank(), 1); CHECK_EQ(element_count(), values.bits()); CHECK_EQ(shape().element_type(), PRED); for (int64_t i = 0; i < static_cast<int64_t>(values.bits()); ++i) { Set({i}, values.get(i)); } } void MutableLiteralBase::PopulateInplaceInternal( absl::FunctionRef<void(void*, absl::Span<const int64_t>, int)> populator, bool parallel) { const Shape& this_shape = shape(); const int64_t rank = this_shape.rank(); DCHECK(LayoutUtil::IsDenseArray(this_shape)); char* const dest_base = static_cast<char*>(untyped_data()); if (rank > 0) { StrideConfig stride_config(this_shape, this_shape, this_shape.dimensions()); const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); const int64_t num_elements = ShapeUtil::ElementsIn(shape()); // If we are rank-1 and we are `parallel`, it is better to use a smaller // `step` than what `StrideConfig` does: stick the entire dimension in the // inner-most loop. if (parallel && this_shape.rank() == 1) { const int64_t thread_count = ShapeUtil::GetForEachIndexParallelThreadCount(); // Let's just divide up the array into small amounts per thread. stride_config.dest_stride = stride_config.minor_loop_size = num_elements > 32 ? std::max<int64_t>(num_elements / thread_count, 1) : num_elements; stride_config.step = {stride_config.minor_loop_size}; } auto init_function = [&](absl::Span<const int64_t> indexes, int thread_id) -> absl::StatusOr<bool> { const int64_t index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), indexes); DimensionVector minor_scan_indexes(rank, 0); std::copy(indexes.begin(), indexes.end(), minor_scan_indexes.begin()); char* dest_ptr = dest_base + index * primitive_size; char* const dest_end = dest_base + // This handles the case where minor_loop_size does not evenly divide // the most minor dimension. std::min(index + stride_config.minor_loop_size, num_elements) * primitive_size; while (dest_ptr < dest_end) { populator(dest_ptr, minor_scan_indexes, thread_id); ++minor_scan_indexes[stride_config.minor_dimension]; dest_ptr += primitive_size; } return true; }; if (parallel) { ShapeUtil::ForEachIndexParallel(this_shape, stride_config.base, stride_config.dimensions, stride_config.step, init_function); } else { ShapeUtil::ForEachIndex( this_shape, stride_config.base, stride_config.dimensions, stride_config.step, [&init_function]( absl::Span<const int64_t> indexes) -> absl::StatusOr<bool> { auto result_ignored = init_function(indexes, /*thread_id=*/-1); return true; }); } } else { // For scalars. populator(dest_base, {}, /*thread_id=*/-1); } } auto init_function = [&](absl::Span<const int64_t> indexes, int thread_id) -> absl::StatusOr<bool> { const int64_t index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), indexes); DimensionVector minor_scan_indexes(rank, 0); std::copy(indexes.begin(), indexes.end(), minor_scan_indexes.begin()); char* dest_ptr = dest_base + index * primitive_size; char* const dest_end = dest_base + // This handles the case where minor_loop_size does not evenly divide // the most minor dimension. std::min(index + stride_config.minor_loop_size, num_elements) * primitive_size; while (dest_ptr < dest_end) { populator(dest_ptr, minor_scan_indexes, thread_id); ++minor_scan_indexes[stride_config.minor_dimension]; dest_ptr += primitive_size; } return true; }; [&init_function]( absl::Span<const int64_t> indexes) -> absl::StatusOr<bool> { auto result_ignored = init_function(indexes, /*thread_id=*/-1); return true; }); absl::Status MutableLiteralBase::PopulateInplace( absl::FunctionRef<void(void*, absl::Span<const int64_t>)> populator) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); PopulateInplaceInternal( [&](void* dest, absl::Span<const int64_t> indexes, int /*thread_id*/) { return populator(dest, indexes); }, /*parallel=*/false); return absl::OkStatus(); } absl::Status MutableLiteralBase::PopulateInplaceParallel( absl::FunctionRef<void(void*, absl::Span<const int64_t>, int)> populator) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); PopulateInplaceInternal(populator, /*parallel=*/element_count() > 32); return absl::OkStatus(); } Literal LiteralBase::Relayout(const Layout& new_layout, const ShapeIndex& shape_index) const { // Create new shape with 'new_layout' set at the given shape index. Shape new_shape = shape(); Shape* subshape = ShapeUtil::GetMutableSubshape(&new_shape, shape_index); TF_CHECK_OK(LayoutUtil::ValidateLayoutForShape(new_layout, *subshape)); *subshape->mutable_layout() = new_layout; // LINT.IfChange // s4 literals are stored in uint8_t/int8_t, therefore element_size_in_bits // must be removed. if (subshape->layout().element_size_in_bits() == 4) { subshape->mutable_layout()->set_element_size_in_bits(0); } // LINT.ThenChange(//tensorflow/compiler/xla/types.h) Literal result(new_shape); TF_CHECK_OK(result.CopyFrom(*this)); return result; } Literal LiteralBase::Relayout(const Shape& shape_with_layout) const { CHECK(ShapeUtil::Compatible(shape_with_layout, shape())) << "Given shape_with_layout " << ShapeUtil::HumanString(shape_with_layout) << " not compatible with literal shape " << ShapeUtil::HumanString(shape()); Literal result = CreateFromShape(shape_with_layout); ShapeUtil::ForEachSubshape( result.shape(), [this, &result](const Shape& subshape, const ShapeIndex& index) { if (subshape.IsArray()) { TF_CHECK_OK(result.CopyFrom(*this, /*dest_shape_index=*/index, /*src_shape_index=*/index)); } }); return result; } [this, &result](const Shape& subshape, const ShapeIndex& index) { if (subshape.IsArray()) { TF_CHECK_OK(result.CopyFrom(*this, /*dest_shape_index=*/index, /*src_shape_index=*/index)); } }); Literal LiteralBase::ToBoundedDynamic(const Shape& bounded_shape) const { CHECK(bounded_shape.is_dynamic()); Literal result(bounded_shape); ShapeUtil::ForEachSubshape( shape(), [&](const Shape& subshape, const ShapeIndex& index) { if (!subshape.IsArray()) { return; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (bounded_shape.is_dynamic_dimension(i)) { result.SetDynamicSize(i, subshape.dimensions(i)); } } }); TF_CHECK_OK(result.CopyFrom(*this, {}, {}, /*only_dynamic_bound=*/true)); return result; } shape(), [&](const Shape& subshape, const ShapeIndex& index) { if (!subshape.IsArray()) { return; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (bounded_shape.is_dynamic_dimension(i)) { result.SetDynamicSize(i, subshape.dimensions(i)); } } }); Literal LiteralBase::ToStatic() const { // Create new shape with 'new_layout' set at the given shape index. Shape new_shape = shape(); ShapeUtil::ForEachMutableSubshape( &new_shape, [this](Shape* subshape, const ShapeIndex& index) { if (!subshape->IsArray()) { return; } for (int64_t i = 0; i < subshape->rank(); ++i) { // GetDynamicSize has a 32-bit return type and may truncate static // dimensions, so make sure to skip. if (!subshape->is_dynamic_dimension(i)) continue; subshape->set_dynamic_dimension(i, false); subshape->set_dimensions(i, GetDynamicSize(i, index)); } }); Literal result(new_shape); TF_CHECK_OK(result.CopyFrom(*this, {}, {}, /*only_dynamic_bound=*/true)); return result; } &new_shape, [this](Shape* subshape, const ShapeIndex& index) { if (!subshape->IsArray()) { return; } for (int64_t i = 0; i < subshape->rank(); ++i) { // GetDynamicSize has a 32-bit return type and may truncate static // dimensions, so make sure to skip. if (!subshape->is_dynamic_dimension(i)) continue; subshape->set_dynamic_dimension(i, false); subshape->set_dimensions(i, GetDynamicSize(i, index)); } }); absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { absl::StatusOr<Literal> LiteralBase::Broadcast( const Shape& result_shape, absl::Span<const int64_t> dimensions) const { const LiteralBase& src = *this; const Shape& src_shape = shape(); if (!src_shape.IsArray()) { return InvalidArgument("Broadcast only supports arrays."); } const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(src_shape.element_type()); switch (primitive_size) { case 0: return BroadcastHelper<0>(src, src_shape, result_shape, dimensions); case 1: return BroadcastHelper<1>(src, src_shape, result_shape, dimensions); case 2: return BroadcastHelper<2>(src, src_shape, result_shape, dimensions); case 4: return BroadcastHelper<4>(src, src_shape, result_shape, dimensions); case 8: return BroadcastHelper<8>(src, src_shape, result_shape, dimensions); case 16: return BroadcastHelper<16>(src, src_shape, result_shape, dimensions); default: LOG(FATAL) << "Unhandled primitive size " << primitive_size; return InvalidArgument("Unhandled primitive size"); break; } } absl::StatusOr<Literal> LiteralBase::Reshape( absl::Span<const int64_t> dimensions) const { if (!LayoutUtil::IsDenseArray(shape())) { return InvalidArgument("Reshape is only supported for dense arrays."); } if (shape().is_dynamic()) { // TODO(b/243182930): We should consider supporting dynamic reshape. return Unimplemented("Dynamic reshape is not implemented."); } Literal output; if (!LayoutUtil::IsMonotonicWithDim0Major(shape().layout())) { output = Relayout(LayoutUtil::GetDefaultLayoutForRank(shape().rank())); } else { output = Clone(); } // Because the layout is monotonic, we can simply reuse the same sequence of // values without changing their order. *output.mutable_shape_do_not_use() = ShapeUtil::MakeShape(shape().element_type(), dimensions); int64_t elements_before = ShapeUtil::ElementsIn(shape()); int64_t elements_after = ShapeUtil::ElementsIn(output.shape()); if (elements_before != elements_after) { return InvalidArgument( "Shapes before and after Literal::Reshape have different numbers " "of elements: %s vs %s.", ShapeUtil::HumanString(shape()), ShapeUtil::HumanString(output.shape())); } return std::move(output); } Literal LiteralBase::Transpose(absl::Span<const int64_t> permutation) const { CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); CHECK(shape().rank() == permutation.size() && IsPermutation(permutation)) << "Given permutation is not a permutation of dimension numbers"; // To transpose the array, we just permute the dimensions and layout, and // do a straight memory copy of the raw data set. // This is considerably faster than iterating over every array element using // the EachCell<>() and Set<>() APIs. Shape permuted_shape = ShapeUtil::PermuteDimensions(permutation, shape()); // Replace the layout with one affine to this shape, such that a // transpose operation can be performed by leaving the flat values // representation intact. // For example, consider the shape F32[11,8]{1,0} under a {1,0} permutation. // The shape with affine layout resulting from that operation will be // F32[8,11]{0,1}, since it leaves the original most minor (the 8 sized), the // most minor. // // Essentially, given MinMaj(Di) the position of the Di dimension within the // minor to major vector, and given T(Di) the index that the original Di // dimension has within the transposed array, a layout is affine if // MinMaj(Di) == TMinMaj(T(Di)), with TMinMaj() being the minor to major // vector of the affine layout. std::vector<int64_t> inverse_permutation = InversePermutation(permutation); CHECK(LayoutUtil::IsDenseArray(permuted_shape)); Layout* layout = permuted_shape.mutable_layout(); layout->clear_minor_to_major(); for (auto index : LayoutUtil::MinorToMajor(shape())) { layout->add_minor_to_major(inverse_permutation[index]); } Literal new_literal(permuted_shape); if (shape().is_dynamic()) { for (int64_t i = 0; i < shape().rank(); i++) { if (shape().is_dynamic_dimension(i)) { // Set the dynamic size of any dynamic dimension in the transposed // literal. new_literal.SetDynamicSize(inverse_permutation[i], GetDynamicSize(i)); } } } DCHECK_EQ(ShapeUtil::ByteSizeOf(new_literal.shape()), ShapeUtil::ByteSizeOf(shape())); std::memcpy(new_literal.untyped_data(), untyped_data(), size_bytes()); return new_literal; } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( Literal LiteralBase::Slice(absl::Span<const int64_t> start_indices, absl::Span<const int64_t> limit_indices) const { CHECK(shape().IsArray()) << "tuple is not supported for slice"; DimensionVector result_dimensions; for (int64_t dnum = 0; dnum < shape().rank(); ++dnum) { CHECK_GE(start_indices[dnum], 0); CHECK_LE(limit_indices[dnum], shape().dimensions(dnum)) << "dnum = " << dnum; int64_t dimension = limit_indices[dnum] - start_indices[dnum]; CHECK_GE(dimension, 0) << "dnum = " << dnum; result_dimensions.push_back(dimension); } auto result_shape = ShapeUtil::MakeShapeWithDenseLayout( shape().element_type(), result_dimensions, LayoutUtil::MinorToMajor(shape())); ShapeUtil::CopyDynamicDimensions(&result_shape, shape()); Literal result_literal(result_shape); primitive_util::ArrayTypeSwitch<void>( [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; return SliceInternal<NativeT>(*this, start_indices, result_literal); }, result_shape.element_type()); return result_literal; } Literal LiteralBase::Clone() const { Literal result(shape()); TF_CHECK_OK(result.CopyFrom(*this)); return result; } std::unique_ptr<Literal> LiteralBase::CloneToUnique() const { auto result = std::make_unique<Literal>(shape()); TF_CHECK_OK(result->CopyFrom(*this)); return result; } bool LiteralBase::IsDetermined(const ShapeIndex& shape_index) const { return piece(shape_index).IsDetermined(); } bool LiteralBase::IsKnown(const ShapeIndex& shape_index) const { return piece(shape_index).IsKnown(); } std::string LiteralBase::GetAsString(absl::Span<const int64_t> multi_index, const ShapeIndex& shape_index) const { const Shape& subshape = ShapeUtil::GetSubshape(shape(), shape_index); CHECK(LayoutUtil::IsDenseArray(subshape)); return primitive_util::ArrayTypeSwitch<std::string>( [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, subshape.element_type()); } [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, std::optional<int64_t> LiteralBase::GetIntegralAsS64( absl::Span<const int64_t> multi_index) const { CHECK(LayoutUtil::IsDenseArray(shape())); return primitive_util::PrimitiveTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, std::optional<double> LiteralBase::GetAsDouble( absl::Span<const int64_t> multi_index) const { const Shape& s = shape(); CHECK(LayoutUtil::IsDenseArray(s)); return primitive_util::PrimitiveTypeSwitch<std::optional<double>>( [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, s.element_type()); } [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, std::optional<double> LiteralBase::GetSumAsDouble( absl::Span<const int64_t> linear_indices) const { const Shape& s = shape(); CHECK(LayoutUtil::IsDenseArray(s)); if (!primitive_util::IsFloatingPointType(s.element_type())) { return std::nullopt; } return primitive_util::FloatingPointTypeSwitch<double>( [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, s.element_type()); } [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, std::optional<complex128> LiteralBase::GetAsComplex128( absl::Span<const int64_t> multi_index) const { return primitive_util::PrimitiveTypeSwitch<std::optional<complex128>>( [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, absl::Status MutableLiteralBase::SetIntegralAsS64( absl::Span<const int64_t> multi_index, int64_t value) { CHECK(LayoutUtil::IsDenseArray(shape())); return primitive_util::PrimitiveTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, absl::Status MutableLiteralBase::SetFromDouble( absl::Span<const int64_t> multi_index, double value) { CHECK(LayoutUtil::IsDenseArray(shape())); if (!primitive_util::IsFloatingPointType(shape().element_type())) { return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); } primitive_util::FloatingPointTypeSwitch<void>( [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, shape().element_type()); return absl::OkStatus(); } [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, void PrintShape(bool print_layout, const Shape& shape, Printer* printer) { if (print_layout) { ShapeUtil::PrintHumanStringWithLayout(printer, shape); } else { ShapeUtil::PrintHumanString(printer, shape); } } void TuplePrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); printer->Append(oneline ? "( " : "(\n"); for (int i = 0; i < ShapeUtil::TupleElementCount(subshape); ++i) { ShapeIndex element_index = shape_index; element_index.push_back(i); if (i > 0) printer->Append(oneline ? ", " : ",\n"); PrintHelper(literal, element_index, print_shape, print_layout, oneline, printer); } printer->Append(oneline ? " )" : "\n)"); } void DenseArrayPrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); int64_t rank = subshape.rank(); const absl::string_view linebreak = oneline ? " " : "\n"; std::function<void(absl::Span<const int64_t> dimensions, std::vector<int64_t>*)> print_recursive = [&](absl::Span<const int64_t> dimensions, std::vector<int64_t>* accum_indices) { // dimensions.size() decreases by 1 at each recursive call, // and accum_indices->size() increases by 1. // Their sum is equal to the rank of the tensor. CHECK_EQ(rank, dimensions.size() + accum_indices->size()); auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; if (dimensions.empty()) { // Display predicates as 0s and 1s so that the string is more dense. std::string elem; if (subshape.element_type() == PRED && rank > 0) { elem = literal.Get<bool>(*accum_indices, shape_index) ? "1" : "0"; } else { elem = literal.GetAsString(*accum_indices, shape_index); } printer->Append(elem); } else { printer->Append(brace_to_string("{")); for (int i = 0; i < dimensions[0]; ++i) { accum_indices->push_back(i); print_recursive(dimensions.subspan(1), accum_indices); accum_indices->pop_back(); if (i < dimensions[0] - 1) { printer->Append(","); printer->Append(dimensions.size() > 1 ? linebreak : " "); } } printer->Append(brace_to_string("}")); } }; if (print_shape) { PrintShape(print_layout, subshape, printer); if (subshape.is_dynamic()) { printer->Append("("); for (int64_t i = 0; i < subshape.dimensions_size(); ++i) { printer->Append(literal.GetDynamicSize(i, shape_index)); if (i < subshape.dimensions_size() - 1) { printer->Append(","); } } printer->Append(")"); } printer->Append(" "); } std::vector<int64_t> indices = {}; std::vector<int64_t> dimensions; dimensions.reserve(subshape.rank()); for (int64_t i = 0; i < subshape.rank(); ++i) { dimensions.push_back(literal.GetDynamicSize(i, shape_index)); } print_recursive(dimensions, &indices); } print_recursive = [&](absl::Span<const int64_t> dimensions, std::vector<int64_t>* accum_indices) { // dimensions.size() decreases by 1 at each recursive call, // and accum_indices->size() increases by 1. // Their sum is equal to the rank of the tensor. CHECK_EQ(rank, dimensions.size() + accum_indices->size()); auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; if (dimensions.empty()) { // Display predicates as 0s and 1s so that the string is more dense. std::string elem; if (subshape.element_type() == PRED && rank > 0) { elem = literal.Get<bool>(*accum_indices, shape_index) ? "1" : "0"; } else { elem = literal.GetAsString(*accum_indices, shape_index); } printer->Append(elem); } else { printer->Append(brace_to_string("{")); for (int i = 0; i < dimensions[0]; ++i) { accum_indices->push_back(i); print_recursive(dimensions.subspan(1), accum_indices); accum_indices->pop_back(); if (i < dimensions[0] - 1) { printer->Append(","); printer->Append(dimensions.size() > 1 ? linebreak : " "); } } printer->Append(brace_to_string("}")); } }; auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; void PrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); CHECK(LayoutUtil::HasLayout(literal.shape())); CHECK(LayoutUtil::HasLayout(subshape)); if (subshape.IsTuple()) { TuplePrintHelper(literal, shape_index, print_shape, print_layout, oneline, printer); } else if (subshape.IsToken()) { printer->Append("token"); } else { CHECK(LayoutUtil::IsDenseArray(subshape)); if (literal.IsKnown(shape_index)) { DenseArrayPrintHelper(literal, shape_index, print_shape, print_layout, oneline, printer); } else { PrintShape(print_layout, subshape, printer); printer->Append(" "); if (literal.IsDetermined(shape_index)) { printer->Append("unknown"); } else { printer->Append("undetermined"); } } } } void LiteralBase::Print(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/false, /*oneline=*/false, printer); } void LiteralBase::PrintOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/false, /*oneline=*/true, printer); } void LiteralBase::PrintWithoutShape(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/false, /*print_layout=*/false, /*oneline=*/false, printer); } void LiteralBase::PrintWithoutShapeOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/false, /*print_layout=*/false, /*oneline=*/true, printer); } void LiteralBase::PrintWithLayout(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/true, /*oneline=*/false, printer); } void LiteralBase::PrintWithLayoutOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/true, /*oneline=*/true, printer); } std::string LiteralBase::ToString() const { StringPrinter printer; Print(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringOneline() const { StringPrinter printer; PrintOneline(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithoutShape() const { StringPrinter printer; PrintWithoutShape(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithoutShapeOneline() const { StringPrinter printer; PrintWithoutShapeOneline(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithLayout() const { StringPrinter printer; PrintWithLayout(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithLayoutOneline() const { StringPrinter printer; PrintWithLayoutOneline(&printer); return std::move(printer).ToString(); } void LiteralBase::EachCellAsString( absl::FunctionRef<void(absl::Span<const int64_t> indices, const std::string& value)> per_cell) const { if (ShapeUtil::IsZeroElementArray(shape())) { return; } auto indices = IndexUtil::LinearIndexToMultidimensionalIndex( shape(), /*linear_index=*/0); do { per_cell(indices, GetAsString(indices)); } while (IndexUtil::BumpIndices(shape(), absl::MakeSpan(indices))); } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { absl::StatusOr<Literal> ConvertSwitch(const LiteralBase& literal, PrimitiveType primitive_dest_type) { TF_RET_CHECK(LayoutUtil::IsDenseArray(literal.shape())); if (literal.shape().element_type() == primitive_dest_type) { return literal.Clone(); } // Source Array type requirement is ensured by IsDenseArray before. if (!primitive_util::IsArrayType(primitive_dest_type) || !primitive_util::IsArrayType(literal.shape().element_type())) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(literal.shape().element_type()), PrimitiveType_Name(primitive_dest_type)); } // At this point, we know both src & dst are array types, while src is not // complex type, so we can allocate the result literal here to avoid // duplicating it N^2 times in the conversion implementation. Literal result( ShapeUtil::ChangeElementType(literal.shape(), primitive_dest_type)); TF_RETURN_IF_ERROR(primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { return ConvertIfDestTypeMatches<primitive_type_constant>(literal, result); }, literal.shape().element_type())); return result; } absl::StatusOr<Literal> LiteralBase::Convert( PrimitiveType primitive_dest_type) const { return ConvertSwitch(*this, primitive_dest_type); } absl::StatusOr<Literal> LiteralBase::BitcastConvert( const Shape& dest_shape) const { if (ShapeUtil::ByteSizeOf(dest_shape) != ShapeUtil::ByteSizeOf(shape())) { return InvalidArgument( "Can not bitcast-convert from shape %s to a shape of different size %s", shape().ToString(), dest_shape.ToString()); } if (dest_shape.IsTuple() || shape().IsTuple()) { return InvalidArgument( "bitcast-convert is not valid for tuple shapes %s->%s", shape().ToString(), dest_shape.ToString()); } if (shape().is_dynamic() || dest_shape.is_dynamic()) { return InvalidArgument( "bitcast-convert is not valid for dynamic shape %s->%s", shape().ToString(), dest_shape.ToString()); } Literal out(dest_shape); std::memcpy(out.root_piece_.buffer(), root_piece().buffer(), root_piece().size_bytes_dense()); // Perform the reshape on little endian encoding even on big endian machines. if constexpr (!kLittleEndian) { // Swap byte ordering as per the input data type. size_t input_elem_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); TF_RETURN_IF_ERROR(tsl::ByteSwapArray( const_cast<char*>(out.root_piece().buffer()), input_elem_size, out.root_piece().size_bytes_dense() / input_elem_size)); // Swap byte ordering as per the output data type. size_t output_elem_size = ShapeUtil::ByteSizeOfPrimitiveType(dest_shape.element_type()); TF_RETURN_IF_ERROR(tsl::ByteSwapArray( const_cast<char*>(out.root_piece().buffer()), output_elem_size, out.root_piece().size_bytes_dense() / output_elem_size)); } return out; } absl::StatusOr<Literal> LiteralBase::ConvertToShape( const Shape& dest_shape) const { if (!dest_shape.IsTuple()) { return Convert(dest_shape.element_type()); } std::vector<Literal> elements; const auto tuple_element_count = ShapeUtil::TupleElementCount(shape()); elements.reserve(tuple_element_count); for (int i = 0; i < tuple_element_count; ++i) { auto element = LiteralSlice(*this, {i}); TF_ASSIGN_OR_RETURN( auto new_element, element.ConvertToShape(ShapeUtil::GetSubshape(dest_shape, {i}))); elements.push_back(std::move(new_element)); } return MutableLiteralBase::MoveIntoTuple(absl::MakeSpan(elements)); } /* static */ Literal MutableLiteralBase::MoveIntoTuple( absl::Span<Literal> elements) { std::vector<const Shape*> element_shapes; element_shapes.reserve(elements.size()); for (const Literal& element : elements) { element_shapes.push_back(&element.shape()); } Literal literal(ShapeUtil::MakeTupleShapeWithPtrs(element_shapes), /*allocate_arrays=*/false); for (int i = 0, end = elements.size(); i < end; ++i) { TF_CHECK_OK( literal.MoveFrom(std::move(elements[i]), /*dest_shape_index=*/{i})); } return literal; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualDynamicSize( const LiteralBase::Piece& other) const { DCHECK(ShapeUtil::Compatible(subshape(), other.subshape())); if (subshape().is_static()) { return true; } for (int64_t i = 0; i < subshape().rank(); ++i) { if (GetDynamicSize(i) != other.GetDynamicSize(i)) { return false; } } return true; } bool LiteralBase::Piece::EqualElements(const LiteralBase::Piece& other) const { if (subshape().is_static() && ShapeUtil::Equal(subshape(), other.subshape()) && subshape().IsArray()) { CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(size_bytes_dense(), other.size_bytes_dense()); if (primitive_util::IsSubByteNonPredType(subshape().element_type())) { CHECK(!primitive_util::IsFloatingPointType(subshape().element_type())); auto one_array = buffer(); auto two_array = other.buffer(); const int bits_per_element = primitive_util::BitWidth(subshape().element_type()); const uint8_t mask = LsbMask<uint8_t>(bits_per_element); for (int64_t i = 0; i < size_bytes_dense(); ++i) { if ((one_array[i] & mask) != (two_array[i] & mask)) return false; } return true; } return memcmp(buffer(), other.buffer(), size_bytes_dense()) == 0; } std::vector<int64_t> multi_index; return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeSrcT = NativeTypeOf<primitive_type_constant>; return EqualElementsInternal<NativeSrcT>(other, &multi_index); }, subshape().element_type()); } bool LiteralBase::Equal(const LiteralBase& other, bool layout_sensitive) const { // Checking the structure of tuple literals. Checks for dense arrays are // performed below. if (!ShapeUtil::EqualStructure(shape(), other.shape())) { return false; } return root_piece().ForEachSubpieceWithBool([&](const ShapeIndex& index, const Piece& piece) { const Piece& other_piece = other.piece(index); const Shape& subshape = piece.subshape(); const Shape& other_subshape = other_piece.subshape(); if (subshape.element_type() != other_subshape.element_type()) { return false; } if (!piece.subshape().IsArray()) { return true; } if (subshape.rank() != other_subshape.rank()) { return false; } if (layout_sensitive && (subshape.layout() != other_subshape.layout())) { return false; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (piece.GetDynamicSize(i) != other_piece.GetDynamicSize(i)) { return false; } } if (!piece.EqualElements(other_piece)) { return false; } return true; }); } return root_piece().ForEachSubpieceWithBool([&](const ShapeIndex& index, const Piece& piece) { const Piece& other_piece = other.piece(index); const Shape& subshape = piece.subshape(); const Shape& other_subshape = other_piece.subshape(); if (subshape.element_type() != other_subshape.element_type()) { return false; } if (!piece.subshape().IsArray()) { return true; } if (subshape.rank() != other_subshape.rank()) { return false; } if (layout_sensitive && (subshape.layout() != other_subshape.layout())) { return false; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (piece.GetDynamicSize(i) != other_piece.GetDynamicSize(i)) { return false; } } if (!piece.EqualElements(other_piece)) { return false; } return true; }); static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(std::complex<T> a, std::complex<T> b) { return EqualIncludingNan(a.real(), b.real()) && EqualIncludingNan(a.imag(), b.imag()); } static bool EqualIncludingNan(std::complex<T> a, std::complex<T> b) { return EqualIncludingNan(a.real(), b.real()) && EqualIncludingNan(a.imag(), b.imag()); } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } bool Literal::Piece::IsAll(const Literal& scalar) const { CHECK(ShapeUtil::IsScalar(scalar.shape())) << scalar.shape().ToString(); if (!subshape().IsArray()) { return false; } CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(subshape().element_type(), scalar.shape().element_type()); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, subshape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, int64_t Literal::Piece::CountAll(const Literal& scalar) const { CHECK(ShapeUtil::IsScalar(scalar.shape())) << scalar.shape().ToString(); if (!subshape().IsArray()) { return 0; } CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(subshape().element_type(), scalar.shape().element_type()); return primitive_util::ArrayTypeSwitch<int64_t>( [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, subshape().element_type()); } [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { bool LiteralBase::IsAll(const Literal& scalar) const { return root_piece().IsAll(scalar); } bool LiteralBase::IsAll(int8_t value) const { if (!shape().IsArray()) { return false; } PrimitiveType ty = shape().element_type(); if (primitive_util::IsFloatingPointType(ty)) { return IsAllFloatImpl(value, /*round_value=*/false); } if (primitive_util::IsUnsignedIntegralType(ty) && value < 0) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllFloat(float value) const { return IsAllFloatImpl(value, /*round_value=*/true); } bool LiteralBase::IsAllFloatImpl(float value, bool round_value) const { PrimitiveType ty = shape().element_type(); if (!primitive_util::IsFloatingPointType(ty)) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::FloatingPointTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllComplex(complex64 value) const { PrimitiveType ty = shape().element_type(); if (!primitive_util::IsComplexType(ty)) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::ComplexTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllFirst() const { if (!shape().IsArray()) { return false; } // Empty shapes are not all the first element since there is no first element. if (ShapeUtil::IsZeroElementArray(shape())) { return false; } absl::InlinedVector<int64_t, 4> start_indices(/*n=*/shape().rank(), 0); absl::InlinedVector<int64_t, 4> end_indices(/*n=*/shape().rank(), 1); Literal first = Slice(start_indices, end_indices); return IsAll(first.Reshape({}).value()); } bool LiteralBase::IsR1Iota() const { if (!shape().IsArray()) { return false; } CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); if (shape().rank() != 1) { return false; } return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, shape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, std::optional<int64_t> LiteralBase::IsR1StridedIota() const { if (!shape().IsArray() || shape().rank() != 1) { return std::nullopt; } CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); const int64_t elements = ShapeUtil::ElementsIn(shape()); const PrimitiveType type = shape().element_type(); if (elements <= 1 || !primitive_util::IsIntegralType(type)) { return std::nullopt; } return primitive_util::IntegralTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, bool LiteralBase::IsZero(absl::Span<const int64_t> indices) const { CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, shape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void LiteralBase::Piece::set_array_value_state(ArrayValueState state) { array_value_state_ = state; } LiteralBase::ArrayValueState LiteralBase::Piece::get_array_value_state() const { return array_value_state_; } void LiteralBase::Piece::WriteToProto(LiteralProto* proto) const { *proto->mutable_shape() = subshape().ToProto(); switch (subshape().element_type()) { case PRED: CopyToRepeatedField(proto->mutable_preds(), data<bool>()); break; case U2: *proto->mutable_u2s() = std::string( reinterpret_cast<const char*>(data<u2>().data()), size_bytes_dense()); break; case U4: *proto->mutable_u4s() = std::string( reinterpret_cast<const char*>(data<u4>().data()), size_bytes_dense()); break; case U8: proto->set_u8s(static_cast<const unsigned char*>(data<uint8_t>().data()), element_count()); break; case U16: *proto->mutable_u16s() = std::string(reinterpret_cast<const char*>(data<uint16_t>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_u16s()); } break; case U32: CopyToRepeatedField(proto->mutable_u32s(), data<uint32_t>()); break; case U64: CopyToRepeatedField(proto->mutable_u64s(), data<uint64_t>()); break; case S2: *proto->mutable_s2s() = std::string( reinterpret_cast<const char*>(data<s2>().data()), size_bytes_dense()); break; case S4: *proto->mutable_s4s() = std::string( reinterpret_cast<const char*>(data<s4>().data()), size_bytes_dense()); break; case S8: proto->set_s8s(static_cast<const signed char*>(data<int8_t>().data()), element_count()); break; case S16: *proto->mutable_s16s() = std::string(reinterpret_cast<const char*>(data<int16_t>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_s16s()); } break; case S32: CopyToRepeatedField(proto->mutable_s32s(), data<int32_t>()); break; case S64: CopyToRepeatedField(proto->mutable_s64s(), data<int64_t>()); break; case F8E5M2: *proto->mutable_f8e5m2s() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e5m2>().data()), size_bytes_dense()); break; case F8E4M3FN: *proto->mutable_f8e4m3fns() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3fn>().data()), size_bytes_dense()); break; case F8E4M3B11FNUZ: *proto->mutable_f8e4m3b11fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3b11fnuz>().data()), size_bytes_dense()); break; case F8E5M2FNUZ: *proto->mutable_f8e5m2fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e5m2fnuz>().data()), size_bytes_dense()); break; case F8E4M3FNUZ: *proto->mutable_f8e4m3fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3fnuz>().data()), size_bytes_dense()); break; case F16: *proto->mutable_f16s() = std::string(reinterpret_cast<const char*>(data<half>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_f16s()); } break; case BF16: *proto->mutable_bf16s() = std::string(reinterpret_cast<const char*>(data<bfloat16>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_bf16s()); } break; case F32: CopyToRepeatedField(proto->mutable_f32s(), data<float>()); break; case F64: CopyToRepeatedField(proto->mutable_f64s(), data<double>()); break; case C64: for (complex64 value : data<complex64>()) { proto->add_c64s(value.real()); proto->add_c64s(value.imag()); } break; case C128: for (complex128 value : data<complex128>()) { proto->add_c128s(value.real()); proto->add_c128s(value.imag()); } break; case TUPLE: case TOKEN: // Nothing to do but assign the shape which is done above. return; default: // TODO(b/111551621): Support serializing more PrimitiveTypes. LOG(FATAL) << "Unhandled primitive type " << PrimitiveType_Name(subshape().element_type()); } } const void* LiteralBase::Piece::untyped_data() const { DCHECK(LayoutUtil::IsDenseArray(subshape())) << ShapeUtil::HumanString(subshape()); return buffer(); } void* LiteralBase::Piece::untyped_data() { DCHECK(LayoutUtil::IsDenseArray(subshape())) << ShapeUtil::HumanString(subshape()); return buffer(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status LiteralBase::Piece::CopyFromProto(const LiteralProto& proto) { // These conditions should have been checked in // MutableLiteralBase::CreateFromProto. TF_RET_CHECK(proto.has_shape()); Shape shape(proto.shape()); TF_RET_CHECK(LayoutUtil::HasLayout(shape)); TF_RET_CHECK(ShapeUtil::Equal(shape, subshape())); switch (subshape().element_type()) { case PRED: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<bool>(), proto.preds())); break; case S2: { const std::string& s(proto.s2s()); TF_RET_CHECK(data<s2>().size() * sizeof(s2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case S4: { const std::string& s(proto.s4s()); TF_RET_CHECK(data<s4>().size() * sizeof(s4) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case S8: { auto s8_data = data<int8_t>(); TF_RET_CHECK(proto.s8s().size() == s8_data.size()); std::copy(proto.s8s().begin(), proto.s8s().end(), s8_data.begin()); break; } case S16: { const std::string& s(proto.s16s()); TF_RET_CHECK(data<int16_t>().size() * sizeof(int16_t) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case S32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<int32_t>(), proto.s32s())); break; case S64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<int64_t>(), proto.s64s())); break; case U2: { const std::string& s(proto.u2s()); TF_RET_CHECK(data<u2>().size() * sizeof(u2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case U4: { const std::string& s(proto.u4s()); TF_RET_CHECK(data<u4>().size() * sizeof(u4) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case U8: { auto u8_data = data<uint8_t>(); TF_RET_CHECK(proto.u8s().size() == u8_data.size()); std::copy(proto.u8s().begin(), proto.u8s().end(), u8_data.begin()); break; } case U16: { const std::string& s(proto.u16s()); TF_RET_CHECK(data<uint16_t>().size() * sizeof(uint16_t) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case U32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<uint32_t>(), proto.u32s())); break; case U64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<uint64_t>(), proto.u64s())); break; case F8E5M2: { const std::string& s(proto.f8e5m2s()); TF_RET_CHECK(data<tsl::float8_e5m2>().size() * sizeof(tsl::float8_e5m2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3FN: { const std::string& s(proto.f8e4m3fns()); TF_RET_CHECK(data<tsl::float8_e4m3fn>().size() * sizeof(tsl::float8_e4m3fn) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3B11FNUZ: { const std::string& s(proto.f8e4m3b11fnuzs()); TF_RET_CHECK(data<tsl::float8_e4m3b11fnuz>().size() * sizeof(tsl::float8_e4m3b11fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E5M2FNUZ: { const std::string& s(proto.f8e5m2fnuzs()); TF_RET_CHECK(data<tsl::float8_e5m2fnuz>().size() * sizeof(tsl::float8_e5m2fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3FNUZ: { const std::string& s(proto.f8e4m3fnuzs()); TF_RET_CHECK(data<tsl::float8_e4m3fnuz>().size() * sizeof(tsl::float8_e4m3fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F16: { const std::string& s(proto.f16s()); TF_RET_CHECK(data<half>().size() * sizeof(half) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case BF16: { const std::string& s(proto.bf16s()); TF_RET_CHECK(data<bfloat16>().size() * sizeof(bfloat16) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case F32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<float>(), proto.f32s())); break; case F64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<double>(), proto.f64s())); break; case C64: { auto complex_data = data<complex64>(); TF_RET_CHECK(proto.c64s_size() == complex_data.size() * 2); for (int64_t i = 0; i < complex_data.size(); ++i) { complex_data[i] = complex64{proto.c64s(i * 2), proto.c64s(i * 2 + 1)}; } break; } case C128: { auto complex_data = data<complex128>(); const int64_t complex_data_size_doubled = complex_data.size() * 2; TF_RET_CHECK(proto.c128s_size() == complex_data_size_doubled); for (int64_t i = 0, end = complex_data.size(); i < end; ++i) { complex_data[i] = complex128{proto.c128s(i * 2), proto.c128s(i * 2 + 1)}; } break; } case TUPLE: return InvalidArgument("Should not be called on tuple shapes: %s", ShapeUtil::HumanString(subshape())); default: return InvalidArgument("Is called on unsupported shape: %s", ShapeUtil::HumanString(subshape())); } return absl::OkStatus(); } bool LiteralBase::Piece::IsKnown() const { if (array_value_state_ != ArrayValueState::kKnown) { return false; } if (subshape().IsTuple()) { bool are_all_leaf_arrays_known = true; ForEachSubpiece([&are_all_leaf_arrays_known](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_known &= piece.IsKnown(); }); return are_all_leaf_arrays_known; } return true; } ForEachSubpiece([&are_all_leaf_arrays_known](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_known &= piece.IsKnown(); }); bool LiteralBase::Piece::IsDetermined() const { if (array_value_state_ == ArrayValueState::kUndetermined) { return false; } if (subshape().IsTuple()) { bool are_all_leaf_arrays_determined = true; ForEachSubpiece([&are_all_leaf_arrays_determined](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_determined &= piece.IsDetermined(); }); return are_all_leaf_arrays_determined; } return true; } ForEachSubpiece([&are_all_leaf_arrays_determined](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_determined &= piece.IsDetermined(); }); LiteralProto LiteralBase::ToProto() const { LiteralProto proto; root_piece().ForEachSubpiece( [&](const ShapeIndex& index, const Piece& piece) { LiteralProto* proto_piece = &proto; for (int64_t i : index) { while (proto_piece->tuple_literals_size() <= i) { proto_piece->add_tuple_literals(); } proto_piece = proto_piece->mutable_tuple_literals(i); } piece.WriteToProto(proto_piece); }); return proto; } [&](const ShapeIndex& index, const Piece& piece) { LiteralProto* proto_piece = &proto; for (int64_t i : index) { while (proto_piece->tuple_literals_size() <= i) { proto_piece->add_tuple_literals(); } proto_piece = proto_piece->mutable_tuple_literals(i); } piece.WriteToProto(proto_piece); }); const void* LiteralBase::untyped_data(const ShapeIndex& shape_index) const { return piece(shape_index).untyped_data(); } void* MutableLiteralBase::untyped_data(const ShapeIndex& shape_index) { return piece(shape_index).untyped_data(); } int64_t LiteralBase::size_bytes(const ShapeIndex& shape_index) const { return piece(shape_index).size_bytes_dense(); } std::string LiteralBase::GetR1U8AsString() const { CHECK(shape().IsArray()); CHECK_EQ(shape().rank(), 1); CHECK_EQ(shape().element_type(), U8); return std::string(absl::bit_cast<const char*>(data<uint8_t>().data()), ShapeUtil::ElementsIn(shape())); } void MutableBorrowingLiteral::CopyPieceSubtree(const Shape& shape, const Piece* src_piece, Piece* dest_piece) { DCHECK(ShapeUtil::Equal(src_piece->subshape(), dest_piece->subshape())) << "src_piece has shape: " << ShapeUtil::HumanString(src_piece->subshape()) << "dest_piece has shape: " << ShapeUtil::HumanString(dest_piece->subshape()); dest_piece->set_array_value_state(src_piece->get_array_value_state()); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); Piece child_piece; child_piece.set_subshape(&subshape); CopyPieceSubtree(subshape, &src_piece->child(i), &child_piece); dest_piece->emplace_back(std::move(child_piece)); } } else if (shape.IsArray()) { dest_piece->set_buffer(const_cast<char*>(src_piece->buffer())); } } MutableLiteralBase::~MutableLiteralBase() = default; MutableBorrowingLiteral::MutableBorrowingLiteral( const MutableBorrowingLiteral& literal) : MutableLiteralBase() { shape_ = literal.shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.root_piece(), root_piece_); } MutableBorrowingLiteral& MutableBorrowingLiteral::operator=( const MutableBorrowingLiteral& literal) { shape_ = literal.shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.root_piece(), root_piece_); return *this; } MutableBorrowingLiteral::MutableBorrowingLiteral(MutableLiteralBase* literal) : MutableLiteralBase() { shape_ = literal->shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal->root_piece(), root_piece_); } MutableBorrowingLiteral::MutableBorrowingLiteral( MutableBorrowingLiteral literal, const ShapeIndex& view_root) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(literal.piece(view_root).subshape()); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.piece(view_root), root_piece_); } MutableBorrowingLiteral::MutableBorrowingLiteral(const char* src_buf_ptr, const Shape& shape) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(shape); CHECK(LayoutUtil::HasLayout(*shape_)); CHECK(!shape_->IsTuple()); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); root_piece_->set_buffer(const_cast<char*>(src_buf_ptr)); } MutableBorrowingLiteral::MutableBorrowingLiteral(absl::Span<char*> src_buf_ptrs, const Shape& shape) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(shape); if (!shape_->IsTuple()) { CHECK_EQ(src_buf_ptrs.size(), 1); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); root_piece_->set_buffer(const_cast<char*>(src_buf_ptrs[0])); } else { CHECK(!ShapeUtil::IsNestedTuple(*shape_)); CHECK_EQ(src_buf_ptrs.size(), ShapeUtil::TupleElementCount(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); for (int i = 0; i < src_buf_ptrs.size(); ++i) { Piece child_piece; const auto& src_shape = shape_->tuple_shapes(i); CHECK(src_shape.IsArray()); child_piece.set_subshape(&src_shape); child_piece.set_buffer(src_buf_ptrs[i]); root_piece_->emplace_back(std::move(child_piece)); } } } MutableBorrowingLiteral::MutableBorrowingLiteral(ShapeTree<char*> src_buf_ptrs) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(src_buf_ptrs.shape()); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); BuildPieceSubtree(*shape_, root_piece_); root_piece_->ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); } [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); MutableBorrowingLiteral::~MutableBorrowingLiteral() { if (root_piece_ != nullptr) { delete root_piece_; } } LiteralSlice::LiteralSlice(const LiteralBase& literal) : LiteralBase(), root_piece_(&literal.root_piece()) {} LiteralSlice::LiteralSlice(const LiteralBase& literal, const ShapeIndex& view_root) : LiteralBase(), root_piece_(&literal.piece(view_root)) {} BorrowingLiteral::BorrowingLiteral(const char* src_buf_ptr, const Shape& shape) : LiteralBase(), shape_(std::make_unique<Shape>(shape)) { CHECK(shape_->IsArray()); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); root_piece_.set_buffer(const_cast<char*>(src_buf_ptr)); } BorrowingLiteral::BorrowingLiteral(absl::Span<const char* const> src_buf_ptrs, const Shape& shape) : LiteralBase(), shape_(std::make_unique<Shape>(shape)) { CHECK(shape_->IsTuple()); CHECK(!ShapeUtil::IsNestedTuple(*shape_)); CHECK_EQ(src_buf_ptrs.size(), ShapeUtil::TupleElementCount(*shape_)); root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); BuildPieceSubtree(*shape_, &root_piece_); for (int i = 0, end = src_buf_ptrs.size(); i < end; ++i) { const auto& src_shape = shape_->tuple_shapes(i); CHECK(src_shape.IsArray()); root_piece_.child(i).set_buffer(const_cast<char*>(src_buf_ptrs[i])); } } BorrowingLiteral::BorrowingLiteral(ShapeTree<const char*> src_buf_ptrs) : LiteralBase(), shape_(std::make_unique<Shape>(src_buf_ptrs.shape())) { root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); BuildPieceSubtree(*shape_, &root_piece_); root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); } [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); });
#include "xla/literal.h" #include <algorithm> #include <cmath> #include <complex> #include <cstdint> #include <functional> #include <limits> #include <random> #include <string> #include <tuple> #include <utility> #include <vector> #include "absl/base/casts.h" #include "absl/hash/hash.h" #include "absl/random/random.h" #include "absl/status/status.h" #include "absl/strings/match.h" #include "absl/types/span.h" #include "xla/array.h" #include "xla/array2d.h" #include "xla/array3d.h" #include "xla/array4d.h" #include "xla/index_util.h" #include "xla/layout.h" #include "xla/layout_util.h" #include "xla/literal_util.h" #include "xla/primitive_util.h" #include "xla/shape.h" #include "xla/shape_tree.h" #include "xla/shape_util.h" #include "xla/test.h" #include "xla/types.h" #include "xla/util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/errors.h" #include "tsl/platform/logging.h" // IWYU pragma: keep #include "tsl/platform/macros.h" #include "tsl/platform/ml_dtypes.h" #include "tsl/platform/statusor.h" #include "tsl/platform/test_benchmark.h" class LiteralUtilTest : public ::testing::Test { protected: LiteralUtilTest() { Array4D<float> arr4d({ // clang-format off { // i0=0 { // i1=0 {1, 2, 3}, // i2=0 {4, 5, 6}, // i2=1 {7, 8, 9}, // i2=2 }, { // i1=1 {11, 12, 13}, {14, 15, 16}, {17, 18, 19}, }, }, { // i0=1 { // i1=0 {101, 102, 103}, {104, 105, 106}, {107, 108, 109}, }, { // i1=1 {201, 202, 203}, // i2=0 {204, 205, 206}, // i2=1 {207, 208, 209}, // i2=2 }, }, // clang-format on }); layout_r2_dim0major_ = LayoutUtil::MakeLayout({1, 0}); layout_r2_dim0minor_ = LayoutUtil::MakeLayout({0, 1}); layout_r3_dim0major_ = LayoutUtil::MakeLayout({2, 1, 0}); layout_r3_dim0minor_ = LayoutUtil::MakeLayout({0, 1, 2}); layout_r4_dim0major_ = LayoutUtil::MakeLayout({3, 2, 1, 0}); layout_r4_dim0minor_ = LayoutUtil::MakeLayout({0, 1, 2, 3}); literal_r4_2x2x3x3_dim0major_ = LiteralUtil::CreateR4FromArray4DWithLayout<float>(arr4d, layout_r4_dim0major_); literal_r4_2x2x3x3_dim0minor_ = LiteralUtil::CreateR4FromArray4DWithLayout<float>(arr4d, layout_r4_dim0minor_); } Layout layout_r2_dim0major_; Layout layout_r2_dim0minor_; Layout layout_r3_dim0major_; Layout layout_r3_dim0minor_; Layout layout_r4_dim0major_; Layout layout_r4_dim0minor_; Literal literal_r4_2x2x3x3_dim0major_; Literal literal_r4_2x2x3x3_dim0minor_; }; TEST_F(LiteralUtilTest, BorrowingLiteralFromOneBufferPtr) { std::vector<int64_t> int64_values = {1, 2, 3}; const Shape literal_shape = ShapeUtil::MakeShape(S64, {3}); BorrowingLiteral literal(reinterpret_cast<const char*>(int64_values.data()), literal_shape); EXPECT_EQ(literal.Get<int64_t>({0}), 1); EXPECT_EQ(literal.Get<int64_t>({1}), 2); EXPECT_EQ(literal.Get<int64_t>({2}), 3); }
LiteralUtilTest_BorrowingLiteralFromShapeTree
xla/literal_test.cc
bool LiteralProtoHasValues(const LiteralProto& proto) { return !proto.s2s().empty() || !proto.s4s().empty() || !proto.s8s().empty() || !proto.s16s().empty() || proto.s32s_size() || proto.s64s_size() || !proto.u2s().empty() || !proto.u4s().empty() || !proto.u8s().empty() || !proto.u16s().empty() || proto.u32s_size() || proto.u64s_size() || !proto.f8e5m2s().empty() || !proto.f8e4m3fns().empty() || !proto.f8e4m3b11fnuzs().empty() || !proto.f8e5m2fnuzs().empty() || !proto.f8e4m3fnuzs().empty() || !proto.f16s().empty() || !proto.bf16s().empty() || proto.f32s_size() || proto.f64s_size() || proto.c64s_size() || proto.c128s_size() || proto.preds_size() || proto.tuple_literals_size(); } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { const Shape& NilShape() { static const Shape* shape = new Shape(TUPLE, {}, {}, {}); return *shape; } const Shape* TryInternShape(const Shape& shape) { if (shape.IsTuple() && shape.tuple_shapes_size() == 0) { return &NilShape(); } if (shape.IsArray() && shape.dimensions_size() == 0 && shape.is_static() && shape.layout().tiles_size() == 0 && shape.layout().memory_space() == 0) { return &ScalarShape(shape.element_type()); } return nullptr; } StrideConfig::StrideConfig(const Shape& source_shape, const Shape& dest_shape, absl::Span<const int64_t> dimensions) : dimensions(dimensions), base(dimensions.size(), 0), step(dimensions.size(), 1) { if (!dimensions.empty()) { // Selects the shape with the largest minor dimension as the one upon // which to run the tight stride loop. if (dimensions[LayoutUtil::Minor(source_shape.layout(), 0)] >= dimensions[LayoutUtil::Minor(dest_shape.layout(), 0)]) { minor_dimension = LayoutUtil::Minor(source_shape.layout(), 0); dest_stride = IndexUtil::GetDimensionStride(dest_shape, minor_dimension); } else { minor_dimension = LayoutUtil::Minor(dest_shape.layout(), 0); source_stride = IndexUtil::GetDimensionStride(source_shape, minor_dimension); } minor_loop_size = dimensions[minor_dimension]; step[minor_dimension] = minor_loop_size; } } LiteralBase::~LiteralBase() = default; const Shape& LiteralBase::shape() const { return root_piece().subshape(); } const char* LiteralBase::Piece::buffer() const { // std::visit is avoided here due to its code size issues. if (auto* r = std::get_if<DenseRep>(&rep_)) { return r->data; } if (auto* r = std::get_if<DenseInlinedRep>(&rep_)) { return r->data; } DCHECK(std::holds_alternative<TupleRep>(rep_) || std::holds_alternative<Uninitialized>(rep_)); return nullptr; } const LiteralBase::Piece& LiteralBase::piece( const ShapeIndex& shape_index) const { const Piece* piece = &root_piece(); for (const auto i : shape_index) { DCHECK_GE(i, 0); DCHECK_LT(i, piece->children_size()); piece = &piece->child(i); } return *piece; } std::ostream& operator<<(std::ostream& out, const Literal& literal) { out << literal.ToString(); return out; } Shape* MutableLiteralBase::mutable_shape_do_not_use() { const Shape* const_shape = shape_.get(); if (!shape_.OwnsPtr()) { shape_ = MaybeOwningShapePtr(std::make_unique<Shape>(*shape_)); } Shape* shape = shape_.get_mutable(); if (shape != const_shape) { std::function<void(const Shape&, Piece*)> set_piece_shapes = [&set_piece_shapes](const Shape& shape, Piece* piece) { piece->set_subshape(&shape); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); set_piece_shapes(subshape, &piece->child(i)); } } }; set_piece_shapes(*shape, &mutable_root_piece()); } return shape; } [&set_piece_shapes](const Shape& shape, Piece* piece) { piece->set_subshape(&shape); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); set_piece_shapes(subshape, &piece->child(i)); } } }; Literal::Literal() : Literal(NilShape()) {} Literal::Literal(const Shape& shape) : Literal(shape, /*allocate_arrays=*/true) {} void Literal::SetShape(const Shape& shape) { Shape shape_storage; const Shape* shape_ptr = &shape; if (LayoutUtil::HasCustomElementSizeInBits(shape)) { shape_storage = shape; shape_storage.mutable_layout()->set_element_size_in_bits(0); shape_ptr = &shape_storage; } if (const Shape* intered_shape_ptr = TryInternShape(*shape_ptr)) { shape_ = intered_shape_ptr; } else { shape_ = std::make_unique<Shape>(*shape_ptr); } } void Literal::SetPiece(const Shape& shape, Piece* piece, bool allocate_arrays, ArrayValueState leaf_array_value_state) { if (shape.IsTuple()) { for (const Shape& subshape : shape.tuple_shapes()) { Piece child_piece; child_piece.set_subshape(&subshape); SetPiece(subshape, &child_piece, allocate_arrays, leaf_array_value_state); piece->emplace_back(std::move(child_piece)); } } else if (shape.IsArray()) { DCHECK(LayoutUtil::IsDenseArray(shape)) << "literal array storage is currently only supported for dense " "arrays: " << shape; piece->set_array_value_state(leaf_array_value_state); if (leaf_array_value_state == LiteralBase::ArrayValueState::kKnown && allocate_arrays) { piece->AllocateBuffers(); } } } Literal::Literal(const Shape& shape, bool allocate_arrays, ArrayValueState leaf_array_value_state) : MutableLiteralBase() { SetShape(shape); CHECK(leaf_array_value_state != ArrayValueState::kKnown || LayoutUtil::HasLayout(*shape_)); root_piece_.set_subshape(shape_.get()); CHECK(&root_piece_.subshape() == shape_.get()); SetPiece(*shape_, &root_piece_, allocate_arrays, leaf_array_value_state); } Literal::~Literal() { DeallocateBuffers(); } void Literal::DeallocateBuffers() { root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { piece->DeallocateBuffers(); }); } Literal::Literal(Literal&& other) : MutableLiteralBase() { *this = std::move(other); } Literal& Literal::operator=(Literal&& other) { DCHECK(&other.root_piece_.subshape() == other.shape_.get()); using std::swap; swap(shape_, other.shape_); swap(root_piece_, other.root_piece_); DCHECK(&root_piece_.subshape() == shape_.get()); return *this; } Literal LiteralBase::CreateFromShape(const Shape& shape) { Literal literal(shape); literal.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (piece->subshape().IsArray()) { memset(piece->untyped_data(), 0, piece->size_bytes_dense()); } }); return literal; } [&](const ShapeIndex& index, Piece* piece) { if (piece->subshape().IsArray()) { memset(piece->untyped_data(), 0, piece->size_bytes_dense()); } }); Literal LiteralBase::CreateFromShapeWithUnknownLeafArrays(const Shape& shape) { Literal literal(shape, /*allocate_arrays=*/false, ArrayValueState::kUnknown); return literal; } Literal LiteralBase::CreateFromShapeWithUndeterminedLeafArrays( const Shape& shape) { Literal literal(shape, /*allocate_arrays=*/false, ArrayValueState::kUndetermined); return literal; } int32_t LiteralBase::GetDynamicSize(int64_t dim_index) const { return GetDynamicSize(dim_index, {}); } int32_t LiteralBase::GetDynamicSize(int64_t dim_index, const ShapeIndex& shape_index) const { return piece(shape_index).GetDynamicSize(dim_index); } std::optional<int64_t> LiteralBase::GetFirstInteger() const { if (!primitive_util::IsIntegralType(shape().element_type())) { return std::nullopt; } return primitive_util::IntegralTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, void LiteralBase::BuildPieceSubtree(const Shape& shape, Piece* piece) { CHECK(shape.IsTuple()); for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); Piece child_piece; child_piece.set_subshape(&subshape); if (subshape.IsTuple()) { BuildPieceSubtree(subshape, &child_piece); } piece->emplace_back(std::move(child_piece)); } } absl::Status LiteralBase::SerializeToString(std::string* output) const { ShapeProto shape_proto = shape().ToProto(); TF_ASSIGN_OR_RETURN(int64_t size, ShapeUtil::SerializedSizeWithProto(shape(), shape_proto)); output->resize(size); return SerializeWithShapeProto(shape_proto, output->data()); } absl::StatusOr<std::string> LiteralBase::SerializeAsString() const { std::string result; TF_RETURN_IF_ERROR(SerializeToString(&result)); return std::move(result); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { void MutableLiteralBase::CopyElementFrom(const LiteralSlice& src_literal, absl::Span<const int64_t> src_index, absl::Span<const int64_t> dest_index) { DCHECK(LayoutUtil::IsDenseArray(shape())); DCHECK_EQ(shape().element_type(), src_literal.shape().element_type()); const int64_t src_linear_index = IndexUtil::MultidimensionalIndexToLinearIndex(src_literal.shape(), src_index); const int64_t dest_linear_index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), dest_index); const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); char* dest_address = static_cast<char*>(untyped_data()) + dest_linear_index * primitive_size; const char* source_address = static_cast<const char*>(src_literal.untyped_data()) + src_linear_index * primitive_size; if (dest_address != source_address) { memcpy(dest_address, source_address, primitive_size); } } /* static */ absl::StatusOr<Literal> MutableLiteralBase::CreateFromProto( const LiteralProto& proto, bool prohibit_empty_literal) { if (!proto.has_shape()) { return InvalidArgument("LiteralProto has no shape"); } Shape shape(proto.shape()); if (ShapeUtil::HasPrimitiveType(shape, OPAQUE_TYPE)) { return InvalidArgument( "Literal shape cannot include OPAQUE_TYPE sub-shape"); } if (!LayoutUtil::HasLayout(shape)) { return InvalidArgument("LiteralProto has no layout"); } if (LayoutUtil::IsSparseArray(shape)) { return Unimplemented("Sparse literals are not supported"); } TF_RETURN_IF_ERROR(ShapeUtil::ValidateShapeWithOptionalLayout(shape)); Literal literal(shape); TF_RETURN_IF_ERROR(literal.root_piece_.ForEachMutableSubpieceWithStatus( [&](const ShapeIndex& index, Piece* piece) -> absl::Status { const LiteralProto* proto_element = &proto; for (int64_t i : index) { CHECK(i < proto_element->tuple_literals_size()); proto_element = &proto_element->tuple_literals(i); } if (piece->subshape().IsTuple()) { if (proto_element->tuple_literals_size() != ShapeUtil::TupleElementCount(piece->subshape())) { return InvalidArgument( "Expected %d tuple elements in LiteralProto, has %d", ShapeUtil::TupleElementCount(piece->subshape()), proto_element->tuple_literals_size()); } return absl::OkStatus(); } if (piece->subshape().element_type() == TOKEN) { return absl::OkStatus(); } CHECK(piece->subshape().IsArray()); // When prohibit_empty_literal is false (allowing literal with no // values), only copy from proto if the literal proto has values. This // mode is used for a learned cost model. if (prohibit_empty_literal || LiteralProtoHasValues(*proto_element)) { TF_RETURN_IF_ERROR(piece->CopyFromProto(*proto_element)); } return absl::OkStatus(); })); return std::move(literal); } TF_RETURN_IF_ERROR(literal.root_piece_.ForEachMutableSubpieceWithStatus( Literal Literal::SubLiteral(ShapeIndexView shape_index) { if (!shape_index.empty()) { auto decomposed = this->DecomposeTuple(); return decomposed.at(shape_index.front()) .SubLiteral(shape_index.subspan(1)); } else { return std::move(*this); } } std::vector<Literal> Literal::DecomposeTuple() { CHECK(shape().IsTuple()); std::vector<Literal> elements; const auto tuple_element_count = ShapeUtil::TupleElementCount(shape()); elements.reserve(tuple_element_count); for (int i = 0; i < tuple_element_count; ++i) { elements.push_back(Literal(ShapeUtil::GetSubshape(shape(), {i}), /*allocate_arrays=*/false)); Literal& element = elements.back(); element.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* dest_piece) { if (dest_piece->subshape().IsTuple()) { return; } ShapeIndex src_index = {i}; for (int64_t j : index) { src_index.push_back(j); } Piece& src_piece = piece(src_index); // Move the respective buffer over to the element Literal. dest_piece->MoveDataFrom(src_piece); }); } // Set this literal to be nil-shaped. *this = Literal(); return elements; } [&](const ShapeIndex& index, Piece* dest_piece) { if (dest_piece->subshape().IsTuple()) { return; } ShapeIndex src_index = {i}; for (int64_t j : index) { src_index.push_back(j); } Piece& src_piece = piece(src_index); // Move the respective buffer over to the element Literal. dest_piece->MoveDataFrom(src_piece); }); void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } int32_t LiteralBase::Piece::GetDynamicSize(int64_t dim_index) const { CHECK(LayoutUtil::IsDenseArray(subshape())); if (!subshape_->is_dynamic_dimension(dim_index)) { // This is a static dimension, return size. return subshape_->dimensions(dim_index); } return dynamic_size_buffer()[dim_index]; } void LiteralBase::Piece::SetDynamicSize(int64_t dim_index, int32_t size) { CHECK(LayoutUtil::IsDenseArray(subshape())); CHECK(subshape_->is_dynamic_dimension(dim_index)); dynamic_size_buffer()[dim_index] = size; } void LiteralBase::Piece::AllocateBuffers() { const int64_t bytes = total_bytes_dense(); if (bytes > kMaxInlinedBytes) { CHECK_EQ(buffer(), nullptr); rep_.emplace<DenseRep>(); set_buffer( static_cast<char*>(tsl::port::AlignedMalloc(bytes, kMinimumAlignment))); } else { rep_.emplace<DenseInlinedRep>(); } } void LiteralBase::Piece::DeallocateBuffers() { if (auto* array_rep = GetDenseRep()) { tsl::port::AlignedFree(array_rep->data); rep_.emplace<Uninitialized>(); } } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } absl::Status LiteralBase::Piece::CopyFrom(const LiteralBase::Piece& src, bool only_dynamic_bound) { CHECK(subshape_ != nullptr); CHECK(src.subshape_ != nullptr); CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK(LayoutUtil::IsDenseArray(src.subshape())) << __func__ << " is only supported for dense arrays: " << src.subshape(); if (!only_dynamic_bound) { CHECK(ShapeUtil::Compatible(subshape(), src.subshape())); } if (src.array_value_state_ == ArrayValueState::kUnknown || src.array_value_state_ == ArrayValueState::kUndetermined) { if (array_value_state_ == ArrayValueState::kKnown) { DeallocateBuffers(); } array_value_state_ = src.array_value_state_; return absl::OkStatus(); } else { CHECK(src.array_value_state_ == ArrayValueState::kKnown); if (array_value_state_ == ArrayValueState::kUndetermined || array_value_state_ == ArrayValueState::kUnknown) { AllocateBuffers(); } array_value_state_ = src.array_value_state_; } if (ShapeUtil::Equal(subshape(), src.subshape())) { // If the layouts are equal it's faster just to memcpy. memcpy(buffer(), src.buffer(), src.size_bytes_dense()); } else { std::vector<int64_t> origin(subshape().rank(), 0); primitive_util::ArrayTypeSwitch<void>( [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, subshape().element_type()); } DCHECK_EQ(dynamic_size_buffer_bytes(), src.dynamic_size_buffer_bytes()); if (subshape().is_dynamic() && src.subshape().is_dynamic()) { memcpy(dynamic_size_buffer(), src.dynamic_size_buffer(), src.dynamic_size_buffer_bytes()); } return absl::OkStatus(); } [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, void MutableLiteralBase::SetDynamicSize(int64_t dim_index, int32_t size) { return SetDynamicSize(dim_index, {}, size); } void MutableLiteralBase::SetDynamicSize(int64_t dim_index, const ShapeIndex& shape_index, int32_t size) { Shape* subshape = ShapeUtil::GetMutableSubshape(mutable_shape_do_not_use(), shape_index); CHECK(LayoutUtil::IsDenseArray(*subshape)) << __func__ << " is only supported for dense arrays: " << *subshape; CHECK_GE(subshape->dimensions(dim_index), size); subshape->set_dynamic_dimension(dim_index, true); CHECK_EQ(&piece(shape_index).subshape(), subshape); piece(shape_index).SetDynamicSize(dim_index, size); } absl::Status MutableLiteralBase::CopyFrom(const LiteralSlice& src_literal, const ShapeIndex& dest_shape_index, const ShapeIndex& src_shape_index, bool only_dynamic_bound) { const Shape& dest_subshape = ShapeUtil::GetSubshape(shape(), dest_shape_index); const Shape& src_subshape = ShapeUtil::GetSubshape(src_literal.shape(), src_shape_index); if (only_dynamic_bound) { auto& bound_shape = dest_subshape.is_static() ? src_subshape : dest_subshape; auto& compact_shape = dest_subshape.is_static() ? dest_subshape : src_subshape; CHECK(ShapeUtil::DynamicShapeIsCompatible(compact_shape, bound_shape)) << compact_shape.ToString() << " vs " << bound_shape.ToString(); } else { if (!ShapeUtil::Compatible(dest_subshape, src_subshape)) { return InvalidArgument( "Destination subshape incompatible with source subshape: %s vs %s", ShapeUtil::HumanString(dest_subshape), ShapeUtil::HumanString(src_subshape)); } } return mutable_root_piece().ForEachMutableSubpieceWithStatus( [&](const ShapeIndex& index, Piece* piece) { if (!piece->subshape().IsArray()) { return absl::OkStatus(); } // Determine if this index is in the part of this literal that we want // to copy over from src_literal. bool in_subtree_to_copy = true; for (int i = 0; i < dest_shape_index.size(); ++i) { if (index[i] != dest_shape_index[i]) { in_subtree_to_copy = false; break; } } if (!in_subtree_to_copy) { return absl::OkStatus(); } // Construct the index of the corresponding piece in the source literal. ShapeIndex src_piece_index = src_shape_index; for (int64_t i = dest_shape_index.size(), end = index.size(); i < end; ++i) { src_piece_index.push_back(index[i]); } TF_RETURN_IF_ERROR( piece->CopyFrom(src_literal.piece(src_piece_index), /*only_dynamic_bound=*/only_dynamic_bound)); return absl::OkStatus(); }); } [&](const ShapeIndex& index, Piece* piece) { if (!piece->subshape().IsArray()) { return absl::OkStatus(); } // Determine if this index is in the part of this literal that we want // to copy over from src_literal. bool in_subtree_to_copy = true; for (int i = 0; i < dest_shape_index.size(); ++i) { if (index[i] != dest_shape_index[i]) { in_subtree_to_copy = false; break; } } if (!in_subtree_to_copy) { return absl::OkStatus(); } // Construct the index of the corresponding piece in the source literal. ShapeIndex src_piece_index = src_shape_index; for (int64_t i = dest_shape_index.size(), end = index.size(); i < end; ++i) { src_piece_index.push_back(index[i]); } TF_RETURN_IF_ERROR( piece->CopyFrom(src_literal.piece(src_piece_index), /*only_dynamic_bound=*/only_dynamic_bound)); return absl::OkStatus(); }); absl::Status Literal::MoveFrom(Literal&& src_literal, const ShapeIndex& dest_shape_index) { const Shape& dest_subshape = ShapeUtil::GetSubshape(shape(), dest_shape_index); if (!ShapeUtil::Equal(dest_subshape, src_literal.shape())) { return InvalidArgument( "Destination subshape not equal to source shape: %s vs %s", ShapeUtil::HumanString(dest_subshape), ShapeUtil::HumanString(src_literal.shape())); } src_literal.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& src_index, Piece* src_piece) { if (!src_piece->subshape().IsArray()) { return; } ShapeIndex dest_index = dest_shape_index; for (int64_t i : src_index) { dest_index.push_back(i); } Piece& dest_piece = piece(dest_index); dest_piece.DeallocateBuffers(); dest_piece.MoveDataFrom(*src_piece); }); src_literal.shape_ = MaybeOwningShapePtr(&NilShape()); src_literal.root_piece_ = Piece(); src_literal.root_piece_.set_subshape(src_literal.shape_.get()); return absl::OkStatus(); } [&](const ShapeIndex& src_index, Piece* src_piece) { if (!src_piece->subshape().IsArray()) { return; } ShapeIndex dest_index = dest_shape_index; for (int64_t i : src_index) { dest_index.push_back(i); } Piece& dest_piece = piece(dest_index); dest_piece.DeallocateBuffers(); dest_piece.MoveDataFrom(*src_piece); }); absl::Status MutableLiteralBase::CopySliceFrom( const LiteralSlice& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << shape(); TF_RET_CHECK(LayoutUtil::IsDenseArray(src_literal.shape())) << src_literal.shape(); TF_RET_CHECK(ShapeUtil::SameElementType(src_literal.shape(), shape())); TF_RET_CHECK(src_literal.shape().rank() == src_base.size()); TF_RET_CHECK(shape().rank() == dest_base.size()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, void MutableLiteralBase::PopulateR1(const tsl::core::Bitmap& values) { CHECK(shape().IsArray()); CHECK_EQ(shape().rank(), 1); CHECK_EQ(element_count(), values.bits()); CHECK_EQ(shape().element_type(), PRED); for (int64_t i = 0; i < static_cast<int64_t>(values.bits()); ++i) { Set({i}, values.get(i)); } } void MutableLiteralBase::PopulateInplaceInternal( absl::FunctionRef<void(void*, absl::Span<const int64_t>, int)> populator, bool parallel) { const Shape& this_shape = shape(); const int64_t rank = this_shape.rank(); DCHECK(LayoutUtil::IsDenseArray(this_shape)); char* const dest_base = static_cast<char*>(untyped_data()); if (rank > 0) { StrideConfig stride_config(this_shape, this_shape, this_shape.dimensions()); const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); const int64_t num_elements = ShapeUtil::ElementsIn(shape()); // If we are rank-1 and we are `parallel`, it is better to use a smaller // `step` than what `StrideConfig` does: stick the entire dimension in the // inner-most loop. if (parallel && this_shape.rank() == 1) { const int64_t thread_count = ShapeUtil::GetForEachIndexParallelThreadCount(); // Let's just divide up the array into small amounts per thread. stride_config.dest_stride = stride_config.minor_loop_size = num_elements > 32 ? std::max<int64_t>(num_elements / thread_count, 1) : num_elements; stride_config.step = {stride_config.minor_loop_size}; } auto init_function = [&](absl::Span<const int64_t> indexes, int thread_id) -> absl::StatusOr<bool> { const int64_t index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), indexes); DimensionVector minor_scan_indexes(rank, 0); std::copy(indexes.begin(), indexes.end(), minor_scan_indexes.begin()); char* dest_ptr = dest_base + index * primitive_size; char* const dest_end = dest_base + // This handles the case where minor_loop_size does not evenly divide // the most minor dimension. std::min(index + stride_config.minor_loop_size, num_elements) * primitive_size; while (dest_ptr < dest_end) { populator(dest_ptr, minor_scan_indexes, thread_id); ++minor_scan_indexes[stride_config.minor_dimension]; dest_ptr += primitive_size; } return true; }; if (parallel) { ShapeUtil::ForEachIndexParallel(this_shape, stride_config.base, stride_config.dimensions, stride_config.step, init_function); } else { ShapeUtil::ForEachIndex( this_shape, stride_config.base, stride_config.dimensions, stride_config.step, [&init_function]( absl::Span<const int64_t> indexes) -> absl::StatusOr<bool> { auto result_ignored = init_function(indexes, /*thread_id=*/-1); return true; }); } } else { // For scalars. populator(dest_base, {}, /*thread_id=*/-1); } } auto init_function = [&](absl::Span<const int64_t> indexes, int thread_id) -> absl::StatusOr<bool> { const int64_t index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), indexes); DimensionVector minor_scan_indexes(rank, 0); std::copy(indexes.begin(), indexes.end(), minor_scan_indexes.begin()); char* dest_ptr = dest_base + index * primitive_size; char* const dest_end = dest_base + // This handles the case where minor_loop_size does not evenly divide // the most minor dimension. std::min(index + stride_config.minor_loop_size, num_elements) * primitive_size; while (dest_ptr < dest_end) { populator(dest_ptr, minor_scan_indexes, thread_id); ++minor_scan_indexes[stride_config.minor_dimension]; dest_ptr += primitive_size; } return true; }; [&init_function]( absl::Span<const int64_t> indexes) -> absl::StatusOr<bool> { auto result_ignored = init_function(indexes, /*thread_id=*/-1); return true; }); absl::Status MutableLiteralBase::PopulateInplace( absl::FunctionRef<void(void*, absl::Span<const int64_t>)> populator) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); PopulateInplaceInternal( [&](void* dest, absl::Span<const int64_t> indexes, int /*thread_id*/) { return populator(dest, indexes); }, /*parallel=*/false); return absl::OkStatus(); } absl::Status MutableLiteralBase::PopulateInplaceParallel( absl::FunctionRef<void(void*, absl::Span<const int64_t>, int)> populator) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); PopulateInplaceInternal(populator, /*parallel=*/element_count() > 32); return absl::OkStatus(); } Literal LiteralBase::Relayout(const Layout& new_layout, const ShapeIndex& shape_index) const { // Create new shape with 'new_layout' set at the given shape index. Shape new_shape = shape(); Shape* subshape = ShapeUtil::GetMutableSubshape(&new_shape, shape_index); TF_CHECK_OK(LayoutUtil::ValidateLayoutForShape(new_layout, *subshape)); *subshape->mutable_layout() = new_layout; // LINT.IfChange // s4 literals are stored in uint8_t/int8_t, therefore element_size_in_bits // must be removed. if (subshape->layout().element_size_in_bits() == 4) { subshape->mutable_layout()->set_element_size_in_bits(0); } // LINT.ThenChange(//tensorflow/compiler/xla/types.h) Literal result(new_shape); TF_CHECK_OK(result.CopyFrom(*this)); return result; } Literal LiteralBase::Relayout(const Shape& shape_with_layout) const { CHECK(ShapeUtil::Compatible(shape_with_layout, shape())) << "Given shape_with_layout " << ShapeUtil::HumanString(shape_with_layout) << " not compatible with literal shape " << ShapeUtil::HumanString(shape()); Literal result = CreateFromShape(shape_with_layout); ShapeUtil::ForEachSubshape( result.shape(), [this, &result](const Shape& subshape, const ShapeIndex& index) { if (subshape.IsArray()) { TF_CHECK_OK(result.CopyFrom(*this, /*dest_shape_index=*/index, /*src_shape_index=*/index)); } }); return result; } [this, &result](const Shape& subshape, const ShapeIndex& index) { if (subshape.IsArray()) { TF_CHECK_OK(result.CopyFrom(*this, /*dest_shape_index=*/index, /*src_shape_index=*/index)); } }); Literal LiteralBase::ToBoundedDynamic(const Shape& bounded_shape) const { CHECK(bounded_shape.is_dynamic()); Literal result(bounded_shape); ShapeUtil::ForEachSubshape( shape(), [&](const Shape& subshape, const ShapeIndex& index) { if (!subshape.IsArray()) { return; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (bounded_shape.is_dynamic_dimension(i)) { result.SetDynamicSize(i, subshape.dimensions(i)); } } }); TF_CHECK_OK(result.CopyFrom(*this, {}, {}, /*only_dynamic_bound=*/true)); return result; } shape(), [&](const Shape& subshape, const ShapeIndex& index) { if (!subshape.IsArray()) { return; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (bounded_shape.is_dynamic_dimension(i)) { result.SetDynamicSize(i, subshape.dimensions(i)); } } }); Literal LiteralBase::ToStatic() const { // Create new shape with 'new_layout' set at the given shape index. Shape new_shape = shape(); ShapeUtil::ForEachMutableSubshape( &new_shape, [this](Shape* subshape, const ShapeIndex& index) { if (!subshape->IsArray()) { return; } for (int64_t i = 0; i < subshape->rank(); ++i) { // GetDynamicSize has a 32-bit return type and may truncate static // dimensions, so make sure to skip. if (!subshape->is_dynamic_dimension(i)) continue; subshape->set_dynamic_dimension(i, false); subshape->set_dimensions(i, GetDynamicSize(i, index)); } }); Literal result(new_shape); TF_CHECK_OK(result.CopyFrom(*this, {}, {}, /*only_dynamic_bound=*/true)); return result; } &new_shape, [this](Shape* subshape, const ShapeIndex& index) { if (!subshape->IsArray()) { return; } for (int64_t i = 0; i < subshape->rank(); ++i) { // GetDynamicSize has a 32-bit return type and may truncate static // dimensions, so make sure to skip. if (!subshape->is_dynamic_dimension(i)) continue; subshape->set_dynamic_dimension(i, false); subshape->set_dimensions(i, GetDynamicSize(i, index)); } }); absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { absl::StatusOr<Literal> LiteralBase::Broadcast( const Shape& result_shape, absl::Span<const int64_t> dimensions) const { const LiteralBase& src = *this; const Shape& src_shape = shape(); if (!src_shape.IsArray()) { return InvalidArgument("Broadcast only supports arrays."); } const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(src_shape.element_type()); switch (primitive_size) { case 0: return BroadcastHelper<0>(src, src_shape, result_shape, dimensions); case 1: return BroadcastHelper<1>(src, src_shape, result_shape, dimensions); case 2: return BroadcastHelper<2>(src, src_shape, result_shape, dimensions); case 4: return BroadcastHelper<4>(src, src_shape, result_shape, dimensions); case 8: return BroadcastHelper<8>(src, src_shape, result_shape, dimensions); case 16: return BroadcastHelper<16>(src, src_shape, result_shape, dimensions); default: LOG(FATAL) << "Unhandled primitive size " << primitive_size; return InvalidArgument("Unhandled primitive size"); break; } } absl::StatusOr<Literal> LiteralBase::Reshape( absl::Span<const int64_t> dimensions) const { if (!LayoutUtil::IsDenseArray(shape())) { return InvalidArgument("Reshape is only supported for dense arrays."); } if (shape().is_dynamic()) { // TODO(b/243182930): We should consider supporting dynamic reshape. return Unimplemented("Dynamic reshape is not implemented."); } Literal output; if (!LayoutUtil::IsMonotonicWithDim0Major(shape().layout())) { output = Relayout(LayoutUtil::GetDefaultLayoutForRank(shape().rank())); } else { output = Clone(); } // Because the layout is monotonic, we can simply reuse the same sequence of // values without changing their order. *output.mutable_shape_do_not_use() = ShapeUtil::MakeShape(shape().element_type(), dimensions); int64_t elements_before = ShapeUtil::ElementsIn(shape()); int64_t elements_after = ShapeUtil::ElementsIn(output.shape()); if (elements_before != elements_after) { return InvalidArgument( "Shapes before and after Literal::Reshape have different numbers " "of elements: %s vs %s.", ShapeUtil::HumanString(shape()), ShapeUtil::HumanString(output.shape())); } return std::move(output); } Literal LiteralBase::Transpose(absl::Span<const int64_t> permutation) const { CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); CHECK(shape().rank() == permutation.size() && IsPermutation(permutation)) << "Given permutation is not a permutation of dimension numbers"; // To transpose the array, we just permute the dimensions and layout, and // do a straight memory copy of the raw data set. // This is considerably faster than iterating over every array element using // the EachCell<>() and Set<>() APIs. Shape permuted_shape = ShapeUtil::PermuteDimensions(permutation, shape()); // Replace the layout with one affine to this shape, such that a // transpose operation can be performed by leaving the flat values // representation intact. // For example, consider the shape F32[11,8]{1,0} under a {1,0} permutation. // The shape with affine layout resulting from that operation will be // F32[8,11]{0,1}, since it leaves the original most minor (the 8 sized), the // most minor. // // Essentially, given MinMaj(Di) the position of the Di dimension within the // minor to major vector, and given T(Di) the index that the original Di // dimension has within the transposed array, a layout is affine if // MinMaj(Di) == TMinMaj(T(Di)), with TMinMaj() being the minor to major // vector of the affine layout. std::vector<int64_t> inverse_permutation = InversePermutation(permutation); CHECK(LayoutUtil::IsDenseArray(permuted_shape)); Layout* layout = permuted_shape.mutable_layout(); layout->clear_minor_to_major(); for (auto index : LayoutUtil::MinorToMajor(shape())) { layout->add_minor_to_major(inverse_permutation[index]); } Literal new_literal(permuted_shape); if (shape().is_dynamic()) { for (int64_t i = 0; i < shape().rank(); i++) { if (shape().is_dynamic_dimension(i)) { // Set the dynamic size of any dynamic dimension in the transposed // literal. new_literal.SetDynamicSize(inverse_permutation[i], GetDynamicSize(i)); } } } DCHECK_EQ(ShapeUtil::ByteSizeOf(new_literal.shape()), ShapeUtil::ByteSizeOf(shape())); std::memcpy(new_literal.untyped_data(), untyped_data(), size_bytes()); return new_literal; } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( Literal LiteralBase::Slice(absl::Span<const int64_t> start_indices, absl::Span<const int64_t> limit_indices) const { CHECK(shape().IsArray()) << "tuple is not supported for slice"; DimensionVector result_dimensions; for (int64_t dnum = 0; dnum < shape().rank(); ++dnum) { CHECK_GE(start_indices[dnum], 0); CHECK_LE(limit_indices[dnum], shape().dimensions(dnum)) << "dnum = " << dnum; int64_t dimension = limit_indices[dnum] - start_indices[dnum]; CHECK_GE(dimension, 0) << "dnum = " << dnum; result_dimensions.push_back(dimension); } auto result_shape = ShapeUtil::MakeShapeWithDenseLayout( shape().element_type(), result_dimensions, LayoutUtil::MinorToMajor(shape())); ShapeUtil::CopyDynamicDimensions(&result_shape, shape()); Literal result_literal(result_shape); primitive_util::ArrayTypeSwitch<void>( [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; return SliceInternal<NativeT>(*this, start_indices, result_literal); }, result_shape.element_type()); return result_literal; } Literal LiteralBase::Clone() const { Literal result(shape()); TF_CHECK_OK(result.CopyFrom(*this)); return result; } std::unique_ptr<Literal> LiteralBase::CloneToUnique() const { auto result = std::make_unique<Literal>(shape()); TF_CHECK_OK(result->CopyFrom(*this)); return result; } bool LiteralBase::IsDetermined(const ShapeIndex& shape_index) const { return piece(shape_index).IsDetermined(); } bool LiteralBase::IsKnown(const ShapeIndex& shape_index) const { return piece(shape_index).IsKnown(); } std::string LiteralBase::GetAsString(absl::Span<const int64_t> multi_index, const ShapeIndex& shape_index) const { const Shape& subshape = ShapeUtil::GetSubshape(shape(), shape_index); CHECK(LayoutUtil::IsDenseArray(subshape)); return primitive_util::ArrayTypeSwitch<std::string>( [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, subshape.element_type()); } [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, std::optional<int64_t> LiteralBase::GetIntegralAsS64( absl::Span<const int64_t> multi_index) const { CHECK(LayoutUtil::IsDenseArray(shape())); return primitive_util::PrimitiveTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, std::optional<double> LiteralBase::GetAsDouble( absl::Span<const int64_t> multi_index) const { const Shape& s = shape(); CHECK(LayoutUtil::IsDenseArray(s)); return primitive_util::PrimitiveTypeSwitch<std::optional<double>>( [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, s.element_type()); } [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, std::optional<double> LiteralBase::GetSumAsDouble( absl::Span<const int64_t> linear_indices) const { const Shape& s = shape(); CHECK(LayoutUtil::IsDenseArray(s)); if (!primitive_util::IsFloatingPointType(s.element_type())) { return std::nullopt; } return primitive_util::FloatingPointTypeSwitch<double>( [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, s.element_type()); } [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, std::optional<complex128> LiteralBase::GetAsComplex128( absl::Span<const int64_t> multi_index) const { return primitive_util::PrimitiveTypeSwitch<std::optional<complex128>>( [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, absl::Status MutableLiteralBase::SetIntegralAsS64( absl::Span<const int64_t> multi_index, int64_t value) { CHECK(LayoutUtil::IsDenseArray(shape())); return primitive_util::PrimitiveTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, absl::Status MutableLiteralBase::SetFromDouble( absl::Span<const int64_t> multi_index, double value) { CHECK(LayoutUtil::IsDenseArray(shape())); if (!primitive_util::IsFloatingPointType(shape().element_type())) { return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); } primitive_util::FloatingPointTypeSwitch<void>( [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, shape().element_type()); return absl::OkStatus(); } [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, void PrintShape(bool print_layout, const Shape& shape, Printer* printer) { if (print_layout) { ShapeUtil::PrintHumanStringWithLayout(printer, shape); } else { ShapeUtil::PrintHumanString(printer, shape); } } void TuplePrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); printer->Append(oneline ? "( " : "(\n"); for (int i = 0; i < ShapeUtil::TupleElementCount(subshape); ++i) { ShapeIndex element_index = shape_index; element_index.push_back(i); if (i > 0) printer->Append(oneline ? ", " : ",\n"); PrintHelper(literal, element_index, print_shape, print_layout, oneline, printer); } printer->Append(oneline ? " )" : "\n)"); } void DenseArrayPrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); int64_t rank = subshape.rank(); const absl::string_view linebreak = oneline ? " " : "\n"; std::function<void(absl::Span<const int64_t> dimensions, std::vector<int64_t>*)> print_recursive = [&](absl::Span<const int64_t> dimensions, std::vector<int64_t>* accum_indices) { // dimensions.size() decreases by 1 at each recursive call, // and accum_indices->size() increases by 1. // Their sum is equal to the rank of the tensor. CHECK_EQ(rank, dimensions.size() + accum_indices->size()); auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; if (dimensions.empty()) { // Display predicates as 0s and 1s so that the string is more dense. std::string elem; if (subshape.element_type() == PRED && rank > 0) { elem = literal.Get<bool>(*accum_indices, shape_index) ? "1" : "0"; } else { elem = literal.GetAsString(*accum_indices, shape_index); } printer->Append(elem); } else { printer->Append(brace_to_string("{")); for (int i = 0; i < dimensions[0]; ++i) { accum_indices->push_back(i); print_recursive(dimensions.subspan(1), accum_indices); accum_indices->pop_back(); if (i < dimensions[0] - 1) { printer->Append(","); printer->Append(dimensions.size() > 1 ? linebreak : " "); } } printer->Append(brace_to_string("}")); } }; if (print_shape) { PrintShape(print_layout, subshape, printer); if (subshape.is_dynamic()) { printer->Append("("); for (int64_t i = 0; i < subshape.dimensions_size(); ++i) { printer->Append(literal.GetDynamicSize(i, shape_index)); if (i < subshape.dimensions_size() - 1) { printer->Append(","); } } printer->Append(")"); } printer->Append(" "); } std::vector<int64_t> indices = {}; std::vector<int64_t> dimensions; dimensions.reserve(subshape.rank()); for (int64_t i = 0; i < subshape.rank(); ++i) { dimensions.push_back(literal.GetDynamicSize(i, shape_index)); } print_recursive(dimensions, &indices); } print_recursive = [&](absl::Span<const int64_t> dimensions, std::vector<int64_t>* accum_indices) { // dimensions.size() decreases by 1 at each recursive call, // and accum_indices->size() increases by 1. // Their sum is equal to the rank of the tensor. CHECK_EQ(rank, dimensions.size() + accum_indices->size()); auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; if (dimensions.empty()) { // Display predicates as 0s and 1s so that the string is more dense. std::string elem; if (subshape.element_type() == PRED && rank > 0) { elem = literal.Get<bool>(*accum_indices, shape_index) ? "1" : "0"; } else { elem = literal.GetAsString(*accum_indices, shape_index); } printer->Append(elem); } else { printer->Append(brace_to_string("{")); for (int i = 0; i < dimensions[0]; ++i) { accum_indices->push_back(i); print_recursive(dimensions.subspan(1), accum_indices); accum_indices->pop_back(); if (i < dimensions[0] - 1) { printer->Append(","); printer->Append(dimensions.size() > 1 ? linebreak : " "); } } printer->Append(brace_to_string("}")); } }; auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; void PrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); CHECK(LayoutUtil::HasLayout(literal.shape())); CHECK(LayoutUtil::HasLayout(subshape)); if (subshape.IsTuple()) { TuplePrintHelper(literal, shape_index, print_shape, print_layout, oneline, printer); } else if (subshape.IsToken()) { printer->Append("token"); } else { CHECK(LayoutUtil::IsDenseArray(subshape)); if (literal.IsKnown(shape_index)) { DenseArrayPrintHelper(literal, shape_index, print_shape, print_layout, oneline, printer); } else { PrintShape(print_layout, subshape, printer); printer->Append(" "); if (literal.IsDetermined(shape_index)) { printer->Append("unknown"); } else { printer->Append("undetermined"); } } } } void LiteralBase::Print(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/false, /*oneline=*/false, printer); } void LiteralBase::PrintOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/false, /*oneline=*/true, printer); } void LiteralBase::PrintWithoutShape(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/false, /*print_layout=*/false, /*oneline=*/false, printer); } void LiteralBase::PrintWithoutShapeOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/false, /*print_layout=*/false, /*oneline=*/true, printer); } void LiteralBase::PrintWithLayout(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/true, /*oneline=*/false, printer); } void LiteralBase::PrintWithLayoutOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/true, /*oneline=*/true, printer); } std::string LiteralBase::ToString() const { StringPrinter printer; Print(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringOneline() const { StringPrinter printer; PrintOneline(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithoutShape() const { StringPrinter printer; PrintWithoutShape(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithoutShapeOneline() const { StringPrinter printer; PrintWithoutShapeOneline(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithLayout() const { StringPrinter printer; PrintWithLayout(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithLayoutOneline() const { StringPrinter printer; PrintWithLayoutOneline(&printer); return std::move(printer).ToString(); } void LiteralBase::EachCellAsString( absl::FunctionRef<void(absl::Span<const int64_t> indices, const std::string& value)> per_cell) const { if (ShapeUtil::IsZeroElementArray(shape())) { return; } auto indices = IndexUtil::LinearIndexToMultidimensionalIndex( shape(), /*linear_index=*/0); do { per_cell(indices, GetAsString(indices)); } while (IndexUtil::BumpIndices(shape(), absl::MakeSpan(indices))); } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { absl::StatusOr<Literal> ConvertSwitch(const LiteralBase& literal, PrimitiveType primitive_dest_type) { TF_RET_CHECK(LayoutUtil::IsDenseArray(literal.shape())); if (literal.shape().element_type() == primitive_dest_type) { return literal.Clone(); } // Source Array type requirement is ensured by IsDenseArray before. if (!primitive_util::IsArrayType(primitive_dest_type) || !primitive_util::IsArrayType(literal.shape().element_type())) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(literal.shape().element_type()), PrimitiveType_Name(primitive_dest_type)); } // At this point, we know both src & dst are array types, while src is not // complex type, so we can allocate the result literal here to avoid // duplicating it N^2 times in the conversion implementation. Literal result( ShapeUtil::ChangeElementType(literal.shape(), primitive_dest_type)); TF_RETURN_IF_ERROR(primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { return ConvertIfDestTypeMatches<primitive_type_constant>(literal, result); }, literal.shape().element_type())); return result; } absl::StatusOr<Literal> LiteralBase::Convert( PrimitiveType primitive_dest_type) const { return ConvertSwitch(*this, primitive_dest_type); } absl::StatusOr<Literal> LiteralBase::BitcastConvert( const Shape& dest_shape) const { if (ShapeUtil::ByteSizeOf(dest_shape) != ShapeUtil::ByteSizeOf(shape())) { return InvalidArgument( "Can not bitcast-convert from shape %s to a shape of different size %s", shape().ToString(), dest_shape.ToString()); } if (dest_shape.IsTuple() || shape().IsTuple()) { return InvalidArgument( "bitcast-convert is not valid for tuple shapes %s->%s", shape().ToString(), dest_shape.ToString()); } if (shape().is_dynamic() || dest_shape.is_dynamic()) { return InvalidArgument( "bitcast-convert is not valid for dynamic shape %s->%s", shape().ToString(), dest_shape.ToString()); } Literal out(dest_shape); std::memcpy(out.root_piece_.buffer(), root_piece().buffer(), root_piece().size_bytes_dense()); // Perform the reshape on little endian encoding even on big endian machines. if constexpr (!kLittleEndian) { // Swap byte ordering as per the input data type. size_t input_elem_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); TF_RETURN_IF_ERROR(tsl::ByteSwapArray( const_cast<char*>(out.root_piece().buffer()), input_elem_size, out.root_piece().size_bytes_dense() / input_elem_size)); // Swap byte ordering as per the output data type. size_t output_elem_size = ShapeUtil::ByteSizeOfPrimitiveType(dest_shape.element_type()); TF_RETURN_IF_ERROR(tsl::ByteSwapArray( const_cast<char*>(out.root_piece().buffer()), output_elem_size, out.root_piece().size_bytes_dense() / output_elem_size)); } return out; } absl::StatusOr<Literal> LiteralBase::ConvertToShape( const Shape& dest_shape) const { if (!dest_shape.IsTuple()) { return Convert(dest_shape.element_type()); } std::vector<Literal> elements; const auto tuple_element_count = ShapeUtil::TupleElementCount(shape()); elements.reserve(tuple_element_count); for (int i = 0; i < tuple_element_count; ++i) { auto element = LiteralSlice(*this, {i}); TF_ASSIGN_OR_RETURN( auto new_element, element.ConvertToShape(ShapeUtil::GetSubshape(dest_shape, {i}))); elements.push_back(std::move(new_element)); } return MutableLiteralBase::MoveIntoTuple(absl::MakeSpan(elements)); } /* static */ Literal MutableLiteralBase::MoveIntoTuple( absl::Span<Literal> elements) { std::vector<const Shape*> element_shapes; element_shapes.reserve(elements.size()); for (const Literal& element : elements) { element_shapes.push_back(&element.shape()); } Literal literal(ShapeUtil::MakeTupleShapeWithPtrs(element_shapes), /*allocate_arrays=*/false); for (int i = 0, end = elements.size(); i < end; ++i) { TF_CHECK_OK( literal.MoveFrom(std::move(elements[i]), /*dest_shape_index=*/{i})); } return literal; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualDynamicSize( const LiteralBase::Piece& other) const { DCHECK(ShapeUtil::Compatible(subshape(), other.subshape())); if (subshape().is_static()) { return true; } for (int64_t i = 0; i < subshape().rank(); ++i) { if (GetDynamicSize(i) != other.GetDynamicSize(i)) { return false; } } return true; } bool LiteralBase::Piece::EqualElements(const LiteralBase::Piece& other) const { if (subshape().is_static() && ShapeUtil::Equal(subshape(), other.subshape()) && subshape().IsArray()) { CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(size_bytes_dense(), other.size_bytes_dense()); if (primitive_util::IsSubByteNonPredType(subshape().element_type())) { CHECK(!primitive_util::IsFloatingPointType(subshape().element_type())); auto one_array = buffer(); auto two_array = other.buffer(); const int bits_per_element = primitive_util::BitWidth(subshape().element_type()); const uint8_t mask = LsbMask<uint8_t>(bits_per_element); for (int64_t i = 0; i < size_bytes_dense(); ++i) { if ((one_array[i] & mask) != (two_array[i] & mask)) return false; } return true; } return memcmp(buffer(), other.buffer(), size_bytes_dense()) == 0; } std::vector<int64_t> multi_index; return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeSrcT = NativeTypeOf<primitive_type_constant>; return EqualElementsInternal<NativeSrcT>(other, &multi_index); }, subshape().element_type()); } bool LiteralBase::Equal(const LiteralBase& other, bool layout_sensitive) const { // Checking the structure of tuple literals. Checks for dense arrays are // performed below. if (!ShapeUtil::EqualStructure(shape(), other.shape())) { return false; } return root_piece().ForEachSubpieceWithBool([&](const ShapeIndex& index, const Piece& piece) { const Piece& other_piece = other.piece(index); const Shape& subshape = piece.subshape(); const Shape& other_subshape = other_piece.subshape(); if (subshape.element_type() != other_subshape.element_type()) { return false; } if (!piece.subshape().IsArray()) { return true; } if (subshape.rank() != other_subshape.rank()) { return false; } if (layout_sensitive && (subshape.layout() != other_subshape.layout())) { return false; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (piece.GetDynamicSize(i) != other_piece.GetDynamicSize(i)) { return false; } } if (!piece.EqualElements(other_piece)) { return false; } return true; }); } return root_piece().ForEachSubpieceWithBool([&](const ShapeIndex& index, const Piece& piece) { const Piece& other_piece = other.piece(index); const Shape& subshape = piece.subshape(); const Shape& other_subshape = other_piece.subshape(); if (subshape.element_type() != other_subshape.element_type()) { return false; } if (!piece.subshape().IsArray()) { return true; } if (subshape.rank() != other_subshape.rank()) { return false; } if (layout_sensitive && (subshape.layout() != other_subshape.layout())) { return false; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (piece.GetDynamicSize(i) != other_piece.GetDynamicSize(i)) { return false; } } if (!piece.EqualElements(other_piece)) { return false; } return true; }); static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(std::complex<T> a, std::complex<T> b) { return EqualIncludingNan(a.real(), b.real()) && EqualIncludingNan(a.imag(), b.imag()); } static bool EqualIncludingNan(std::complex<T> a, std::complex<T> b) { return EqualIncludingNan(a.real(), b.real()) && EqualIncludingNan(a.imag(), b.imag()); } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } bool Literal::Piece::IsAll(const Literal& scalar) const { CHECK(ShapeUtil::IsScalar(scalar.shape())) << scalar.shape().ToString(); if (!subshape().IsArray()) { return false; } CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(subshape().element_type(), scalar.shape().element_type()); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, subshape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, int64_t Literal::Piece::CountAll(const Literal& scalar) const { CHECK(ShapeUtil::IsScalar(scalar.shape())) << scalar.shape().ToString(); if (!subshape().IsArray()) { return 0; } CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(subshape().element_type(), scalar.shape().element_type()); return primitive_util::ArrayTypeSwitch<int64_t>( [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, subshape().element_type()); } [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { bool LiteralBase::IsAll(const Literal& scalar) const { return root_piece().IsAll(scalar); } bool LiteralBase::IsAll(int8_t value) const { if (!shape().IsArray()) { return false; } PrimitiveType ty = shape().element_type(); if (primitive_util::IsFloatingPointType(ty)) { return IsAllFloatImpl(value, /*round_value=*/false); } if (primitive_util::IsUnsignedIntegralType(ty) && value < 0) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllFloat(float value) const { return IsAllFloatImpl(value, /*round_value=*/true); } bool LiteralBase::IsAllFloatImpl(float value, bool round_value) const { PrimitiveType ty = shape().element_type(); if (!primitive_util::IsFloatingPointType(ty)) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::FloatingPointTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllComplex(complex64 value) const { PrimitiveType ty = shape().element_type(); if (!primitive_util::IsComplexType(ty)) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::ComplexTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllFirst() const { if (!shape().IsArray()) { return false; } // Empty shapes are not all the first element since there is no first element. if (ShapeUtil::IsZeroElementArray(shape())) { return false; } absl::InlinedVector<int64_t, 4> start_indices(/*n=*/shape().rank(), 0); absl::InlinedVector<int64_t, 4> end_indices(/*n=*/shape().rank(), 1); Literal first = Slice(start_indices, end_indices); return IsAll(first.Reshape({}).value()); } bool LiteralBase::IsR1Iota() const { if (!shape().IsArray()) { return false; } CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); if (shape().rank() != 1) { return false; } return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, shape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, std::optional<int64_t> LiteralBase::IsR1StridedIota() const { if (!shape().IsArray() || shape().rank() != 1) { return std::nullopt; } CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); const int64_t elements = ShapeUtil::ElementsIn(shape()); const PrimitiveType type = shape().element_type(); if (elements <= 1 || !primitive_util::IsIntegralType(type)) { return std::nullopt; } return primitive_util::IntegralTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, bool LiteralBase::IsZero(absl::Span<const int64_t> indices) const { CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, shape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void LiteralBase::Piece::set_array_value_state(ArrayValueState state) { array_value_state_ = state; } LiteralBase::ArrayValueState LiteralBase::Piece::get_array_value_state() const { return array_value_state_; } void LiteralBase::Piece::WriteToProto(LiteralProto* proto) const { *proto->mutable_shape() = subshape().ToProto(); switch (subshape().element_type()) { case PRED: CopyToRepeatedField(proto->mutable_preds(), data<bool>()); break; case U2: *proto->mutable_u2s() = std::string( reinterpret_cast<const char*>(data<u2>().data()), size_bytes_dense()); break; case U4: *proto->mutable_u4s() = std::string( reinterpret_cast<const char*>(data<u4>().data()), size_bytes_dense()); break; case U8: proto->set_u8s(static_cast<const unsigned char*>(data<uint8_t>().data()), element_count()); break; case U16: *proto->mutable_u16s() = std::string(reinterpret_cast<const char*>(data<uint16_t>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_u16s()); } break; case U32: CopyToRepeatedField(proto->mutable_u32s(), data<uint32_t>()); break; case U64: CopyToRepeatedField(proto->mutable_u64s(), data<uint64_t>()); break; case S2: *proto->mutable_s2s() = std::string( reinterpret_cast<const char*>(data<s2>().data()), size_bytes_dense()); break; case S4: *proto->mutable_s4s() = std::string( reinterpret_cast<const char*>(data<s4>().data()), size_bytes_dense()); break; case S8: proto->set_s8s(static_cast<const signed char*>(data<int8_t>().data()), element_count()); break; case S16: *proto->mutable_s16s() = std::string(reinterpret_cast<const char*>(data<int16_t>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_s16s()); } break; case S32: CopyToRepeatedField(proto->mutable_s32s(), data<int32_t>()); break; case S64: CopyToRepeatedField(proto->mutable_s64s(), data<int64_t>()); break; case F8E5M2: *proto->mutable_f8e5m2s() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e5m2>().data()), size_bytes_dense()); break; case F8E4M3FN: *proto->mutable_f8e4m3fns() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3fn>().data()), size_bytes_dense()); break; case F8E4M3B11FNUZ: *proto->mutable_f8e4m3b11fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3b11fnuz>().data()), size_bytes_dense()); break; case F8E5M2FNUZ: *proto->mutable_f8e5m2fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e5m2fnuz>().data()), size_bytes_dense()); break; case F8E4M3FNUZ: *proto->mutable_f8e4m3fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3fnuz>().data()), size_bytes_dense()); break; case F16: *proto->mutable_f16s() = std::string(reinterpret_cast<const char*>(data<half>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_f16s()); } break; case BF16: *proto->mutable_bf16s() = std::string(reinterpret_cast<const char*>(data<bfloat16>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_bf16s()); } break; case F32: CopyToRepeatedField(proto->mutable_f32s(), data<float>()); break; case F64: CopyToRepeatedField(proto->mutable_f64s(), data<double>()); break; case C64: for (complex64 value : data<complex64>()) { proto->add_c64s(value.real()); proto->add_c64s(value.imag()); } break; case C128: for (complex128 value : data<complex128>()) { proto->add_c128s(value.real()); proto->add_c128s(value.imag()); } break; case TUPLE: case TOKEN: // Nothing to do but assign the shape which is done above. return; default: // TODO(b/111551621): Support serializing more PrimitiveTypes. LOG(FATAL) << "Unhandled primitive type " << PrimitiveType_Name(subshape().element_type()); } } const void* LiteralBase::Piece::untyped_data() const { DCHECK(LayoutUtil::IsDenseArray(subshape())) << ShapeUtil::HumanString(subshape()); return buffer(); } void* LiteralBase::Piece::untyped_data() { DCHECK(LayoutUtil::IsDenseArray(subshape())) << ShapeUtil::HumanString(subshape()); return buffer(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status LiteralBase::Piece::CopyFromProto(const LiteralProto& proto) { // These conditions should have been checked in // MutableLiteralBase::CreateFromProto. TF_RET_CHECK(proto.has_shape()); Shape shape(proto.shape()); TF_RET_CHECK(LayoutUtil::HasLayout(shape)); TF_RET_CHECK(ShapeUtil::Equal(shape, subshape())); switch (subshape().element_type()) { case PRED: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<bool>(), proto.preds())); break; case S2: { const std::string& s(proto.s2s()); TF_RET_CHECK(data<s2>().size() * sizeof(s2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case S4: { const std::string& s(proto.s4s()); TF_RET_CHECK(data<s4>().size() * sizeof(s4) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case S8: { auto s8_data = data<int8_t>(); TF_RET_CHECK(proto.s8s().size() == s8_data.size()); std::copy(proto.s8s().begin(), proto.s8s().end(), s8_data.begin()); break; } case S16: { const std::string& s(proto.s16s()); TF_RET_CHECK(data<int16_t>().size() * sizeof(int16_t) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case S32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<int32_t>(), proto.s32s())); break; case S64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<int64_t>(), proto.s64s())); break; case U2: { const std::string& s(proto.u2s()); TF_RET_CHECK(data<u2>().size() * sizeof(u2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case U4: { const std::string& s(proto.u4s()); TF_RET_CHECK(data<u4>().size() * sizeof(u4) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case U8: { auto u8_data = data<uint8_t>(); TF_RET_CHECK(proto.u8s().size() == u8_data.size()); std::copy(proto.u8s().begin(), proto.u8s().end(), u8_data.begin()); break; } case U16: { const std::string& s(proto.u16s()); TF_RET_CHECK(data<uint16_t>().size() * sizeof(uint16_t) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case U32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<uint32_t>(), proto.u32s())); break; case U64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<uint64_t>(), proto.u64s())); break; case F8E5M2: { const std::string& s(proto.f8e5m2s()); TF_RET_CHECK(data<tsl::float8_e5m2>().size() * sizeof(tsl::float8_e5m2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3FN: { const std::string& s(proto.f8e4m3fns()); TF_RET_CHECK(data<tsl::float8_e4m3fn>().size() * sizeof(tsl::float8_e4m3fn) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3B11FNUZ: { const std::string& s(proto.f8e4m3b11fnuzs()); TF_RET_CHECK(data<tsl::float8_e4m3b11fnuz>().size() * sizeof(tsl::float8_e4m3b11fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E5M2FNUZ: { const std::string& s(proto.f8e5m2fnuzs()); TF_RET_CHECK(data<tsl::float8_e5m2fnuz>().size() * sizeof(tsl::float8_e5m2fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3FNUZ: { const std::string& s(proto.f8e4m3fnuzs()); TF_RET_CHECK(data<tsl::float8_e4m3fnuz>().size() * sizeof(tsl::float8_e4m3fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F16: { const std::string& s(proto.f16s()); TF_RET_CHECK(data<half>().size() * sizeof(half) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case BF16: { const std::string& s(proto.bf16s()); TF_RET_CHECK(data<bfloat16>().size() * sizeof(bfloat16) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case F32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<float>(), proto.f32s())); break; case F64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<double>(), proto.f64s())); break; case C64: { auto complex_data = data<complex64>(); TF_RET_CHECK(proto.c64s_size() == complex_data.size() * 2); for (int64_t i = 0; i < complex_data.size(); ++i) { complex_data[i] = complex64{proto.c64s(i * 2), proto.c64s(i * 2 + 1)}; } break; } case C128: { auto complex_data = data<complex128>(); const int64_t complex_data_size_doubled = complex_data.size() * 2; TF_RET_CHECK(proto.c128s_size() == complex_data_size_doubled); for (int64_t i = 0, end = complex_data.size(); i < end; ++i) { complex_data[i] = complex128{proto.c128s(i * 2), proto.c128s(i * 2 + 1)}; } break; } case TUPLE: return InvalidArgument("Should not be called on tuple shapes: %s", ShapeUtil::HumanString(subshape())); default: return InvalidArgument("Is called on unsupported shape: %s", ShapeUtil::HumanString(subshape())); } return absl::OkStatus(); } bool LiteralBase::Piece::IsKnown() const { if (array_value_state_ != ArrayValueState::kKnown) { return false; } if (subshape().IsTuple()) { bool are_all_leaf_arrays_known = true; ForEachSubpiece([&are_all_leaf_arrays_known](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_known &= piece.IsKnown(); }); return are_all_leaf_arrays_known; } return true; } ForEachSubpiece([&are_all_leaf_arrays_known](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_known &= piece.IsKnown(); }); bool LiteralBase::Piece::IsDetermined() const { if (array_value_state_ == ArrayValueState::kUndetermined) { return false; } if (subshape().IsTuple()) { bool are_all_leaf_arrays_determined = true; ForEachSubpiece([&are_all_leaf_arrays_determined](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_determined &= piece.IsDetermined(); }); return are_all_leaf_arrays_determined; } return true; } ForEachSubpiece([&are_all_leaf_arrays_determined](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_determined &= piece.IsDetermined(); }); LiteralProto LiteralBase::ToProto() const { LiteralProto proto; root_piece().ForEachSubpiece( [&](const ShapeIndex& index, const Piece& piece) { LiteralProto* proto_piece = &proto; for (int64_t i : index) { while (proto_piece->tuple_literals_size() <= i) { proto_piece->add_tuple_literals(); } proto_piece = proto_piece->mutable_tuple_literals(i); } piece.WriteToProto(proto_piece); }); return proto; } [&](const ShapeIndex& index, const Piece& piece) { LiteralProto* proto_piece = &proto; for (int64_t i : index) { while (proto_piece->tuple_literals_size() <= i) { proto_piece->add_tuple_literals(); } proto_piece = proto_piece->mutable_tuple_literals(i); } piece.WriteToProto(proto_piece); }); const void* LiteralBase::untyped_data(const ShapeIndex& shape_index) const { return piece(shape_index).untyped_data(); } void* MutableLiteralBase::untyped_data(const ShapeIndex& shape_index) { return piece(shape_index).untyped_data(); } int64_t LiteralBase::size_bytes(const ShapeIndex& shape_index) const { return piece(shape_index).size_bytes_dense(); } std::string LiteralBase::GetR1U8AsString() const { CHECK(shape().IsArray()); CHECK_EQ(shape().rank(), 1); CHECK_EQ(shape().element_type(), U8); return std::string(absl::bit_cast<const char*>(data<uint8_t>().data()), ShapeUtil::ElementsIn(shape())); } void MutableBorrowingLiteral::CopyPieceSubtree(const Shape& shape, const Piece* src_piece, Piece* dest_piece) { DCHECK(ShapeUtil::Equal(src_piece->subshape(), dest_piece->subshape())) << "src_piece has shape: " << ShapeUtil::HumanString(src_piece->subshape()) << "dest_piece has shape: " << ShapeUtil::HumanString(dest_piece->subshape()); dest_piece->set_array_value_state(src_piece->get_array_value_state()); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); Piece child_piece; child_piece.set_subshape(&subshape); CopyPieceSubtree(subshape, &src_piece->child(i), &child_piece); dest_piece->emplace_back(std::move(child_piece)); } } else if (shape.IsArray()) { dest_piece->set_buffer(const_cast<char*>(src_piece->buffer())); } } MutableLiteralBase::~MutableLiteralBase() = default; MutableBorrowingLiteral::MutableBorrowingLiteral( const MutableBorrowingLiteral& literal) : MutableLiteralBase() { shape_ = literal.shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.root_piece(), root_piece_); } MutableBorrowingLiteral& MutableBorrowingLiteral::operator=( const MutableBorrowingLiteral& literal) { shape_ = literal.shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.root_piece(), root_piece_); return *this; } MutableBorrowingLiteral::MutableBorrowingLiteral(MutableLiteralBase* literal) : MutableLiteralBase() { shape_ = literal->shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal->root_piece(), root_piece_); } MutableBorrowingLiteral::MutableBorrowingLiteral( MutableBorrowingLiteral literal, const ShapeIndex& view_root) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(literal.piece(view_root).subshape()); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.piece(view_root), root_piece_); } MutableBorrowingLiteral::MutableBorrowingLiteral(const char* src_buf_ptr, const Shape& shape) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(shape); CHECK(LayoutUtil::HasLayout(*shape_)); CHECK(!shape_->IsTuple()); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); root_piece_->set_buffer(const_cast<char*>(src_buf_ptr)); } MutableBorrowingLiteral::MutableBorrowingLiteral(absl::Span<char*> src_buf_ptrs, const Shape& shape) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(shape); if (!shape_->IsTuple()) { CHECK_EQ(src_buf_ptrs.size(), 1); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); root_piece_->set_buffer(const_cast<char*>(src_buf_ptrs[0])); } else { CHECK(!ShapeUtil::IsNestedTuple(*shape_)); CHECK_EQ(src_buf_ptrs.size(), ShapeUtil::TupleElementCount(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); for (int i = 0; i < src_buf_ptrs.size(); ++i) { Piece child_piece; const auto& src_shape = shape_->tuple_shapes(i); CHECK(src_shape.IsArray()); child_piece.set_subshape(&src_shape); child_piece.set_buffer(src_buf_ptrs[i]); root_piece_->emplace_back(std::move(child_piece)); } } } MutableBorrowingLiteral::MutableBorrowingLiteral(ShapeTree<char*> src_buf_ptrs) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(src_buf_ptrs.shape()); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); BuildPieceSubtree(*shape_, root_piece_); root_piece_->ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); } [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); MutableBorrowingLiteral::~MutableBorrowingLiteral() { if (root_piece_ != nullptr) { delete root_piece_; } } LiteralSlice::LiteralSlice(const LiteralBase& literal) : LiteralBase(), root_piece_(&literal.root_piece()) {} LiteralSlice::LiteralSlice(const LiteralBase& literal, const ShapeIndex& view_root) : LiteralBase(), root_piece_(&literal.piece(view_root)) {} BorrowingLiteral::BorrowingLiteral(const char* src_buf_ptr, const Shape& shape) : LiteralBase(), shape_(std::make_unique<Shape>(shape)) { CHECK(shape_->IsArray()); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); root_piece_.set_buffer(const_cast<char*>(src_buf_ptr)); } BorrowingLiteral::BorrowingLiteral(absl::Span<const char* const> src_buf_ptrs, const Shape& shape) : LiteralBase(), shape_(std::make_unique<Shape>(shape)) { CHECK(shape_->IsTuple()); CHECK(!ShapeUtil::IsNestedTuple(*shape_)); CHECK_EQ(src_buf_ptrs.size(), ShapeUtil::TupleElementCount(*shape_)); root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); BuildPieceSubtree(*shape_, &root_piece_); for (int i = 0, end = src_buf_ptrs.size(); i < end; ++i) { const auto& src_shape = shape_->tuple_shapes(i); CHECK(src_shape.IsArray()); root_piece_.child(i).set_buffer(const_cast<char*>(src_buf_ptrs[i])); } } BorrowingLiteral::BorrowingLiteral(ShapeTree<const char*> src_buf_ptrs) : LiteralBase(), shape_(std::make_unique<Shape>(src_buf_ptrs.shape())) { root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); BuildPieceSubtree(*shape_, &root_piece_); root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); } [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); });
#include "xla/literal.h" #include <algorithm> #include <cmath> #include <complex> #include <cstdint> #include <functional> #include <limits> #include <random> #include <string> #include <tuple> #include <utility> #include <vector> #include "absl/base/casts.h" #include "absl/hash/hash.h" #include "absl/random/random.h" #include "absl/status/status.h" #include "absl/strings/match.h" #include "absl/types/span.h" #include "xla/array.h" #include "xla/array2d.h" #include "xla/array3d.h" #include "xla/array4d.h" #include "xla/index_util.h" #include "xla/layout.h" #include "xla/layout_util.h" #include "xla/literal_util.h" #include "xla/primitive_util.h" #include "xla/shape.h" #include "xla/shape_tree.h" #include "xla/shape_util.h" #include "xla/test.h" #include "xla/types.h" #include "xla/util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/errors.h" #include "tsl/platform/logging.h" // IWYU pragma: keep #include "tsl/platform/macros.h" #include "tsl/platform/ml_dtypes.h" #include "tsl/platform/statusor.h" #include "tsl/platform/test_benchmark.h" class LiteralUtilTest : public ::testing::Test { protected: LiteralUtilTest() { Array4D<float> arr4d({ // clang-format off { // i0=0 { // i1=0 {1, 2, 3}, // i2=0 {4, 5, 6}, // i2=1 {7, 8, 9}, // i2=2 }, { // i1=1 {11, 12, 13}, {14, 15, 16}, {17, 18, 19}, }, }, { // i0=1 { // i1=0 {101, 102, 103}, {104, 105, 106}, {107, 108, 109}, }, { // i1=1 {201, 202, 203}, // i2=0 {204, 205, 206}, // i2=1 {207, 208, 209}, // i2=2 }, }, // clang-format on }); layout_r2_dim0major_ = LayoutUtil::MakeLayout({1, 0}); layout_r2_dim0minor_ = LayoutUtil::MakeLayout({0, 1}); layout_r3_dim0major_ = LayoutUtil::MakeLayout({2, 1, 0}); layout_r3_dim0minor_ = LayoutUtil::MakeLayout({0, 1, 2}); layout_r4_dim0major_ = LayoutUtil::MakeLayout({3, 2, 1, 0}); layout_r4_dim0minor_ = LayoutUtil::MakeLayout({0, 1, 2, 3}); literal_r4_2x2x3x3_dim0major_ = LiteralUtil::CreateR4FromArray4DWithLayout<float>(arr4d, layout_r4_dim0major_); literal_r4_2x2x3x3_dim0minor_ = LiteralUtil::CreateR4FromArray4DWithLayout<float>(arr4d, layout_r4_dim0minor_); } Layout layout_r2_dim0major_; Layout layout_r2_dim0minor_; Layout layout_r3_dim0major_; Layout layout_r3_dim0minor_; Layout layout_r4_dim0major_; Layout layout_r4_dim0minor_; Literal literal_r4_2x2x3x3_dim0major_; Literal literal_r4_2x2x3x3_dim0minor_; }; TEST_F(LiteralUtilTest, BorrowingLiteralFromShapeTree) { std::vector<float> data = {1.0, 2.0, 3.0}; Shape shape = ShapeUtil::MakeShape(PrimitiveType::F32, {3}); Shape tuple = ShapeUtil::MakeTupleShape({shape, shape}); Shape nested_tuple = ShapeUtil::MakeTupleShape({tuple, shape}); ShapeTree<const char*> ptr_tree(nested_tuple); *ptr_tree.mutable_element({0, 0}) = reinterpret_cast<char*>(data.data()); *ptr_tree.mutable_element({0, 1}) = reinterpret_cast<char*>(data.data()); *ptr_tree.mutable_element({1}) = reinterpret_cast<char*>(data.data()); BorrowingLiteral literal(ptr_tree); EXPECT_THAT(literal.data<float>({0, 0}), ElementsAre(1.0, 2.0, 3.0)); EXPECT_THAT(literal.data<float>({0, 1}), ElementsAre(1.0, 2.0, 3.0)); EXPECT_THAT(literal.data<float>({1}), ElementsAre(1.0, 2.0, 3.0)); }
LiteralUtilTest_BroadcastScalarToMatrix
xla/literal_test.cc
bool LiteralProtoHasValues(const LiteralProto& proto) { return !proto.s2s().empty() || !proto.s4s().empty() || !proto.s8s().empty() || !proto.s16s().empty() || proto.s32s_size() || proto.s64s_size() || !proto.u2s().empty() || !proto.u4s().empty() || !proto.u8s().empty() || !proto.u16s().empty() || proto.u32s_size() || proto.u64s_size() || !proto.f8e5m2s().empty() || !proto.f8e4m3fns().empty() || !proto.f8e4m3b11fnuzs().empty() || !proto.f8e5m2fnuzs().empty() || !proto.f8e4m3fnuzs().empty() || !proto.f16s().empty() || !proto.bf16s().empty() || proto.f32s_size() || proto.f64s_size() || proto.c64s_size() || proto.c128s_size() || proto.preds_size() || proto.tuple_literals_size(); } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { const Shape& NilShape() { static const Shape* shape = new Shape(TUPLE, {}, {}, {}); return *shape; } const Shape* TryInternShape(const Shape& shape) { if (shape.IsTuple() && shape.tuple_shapes_size() == 0) { return &NilShape(); } if (shape.IsArray() && shape.dimensions_size() == 0 && shape.is_static() && shape.layout().tiles_size() == 0 && shape.layout().memory_space() == 0) { return &ScalarShape(shape.element_type()); } return nullptr; } StrideConfig::StrideConfig(const Shape& source_shape, const Shape& dest_shape, absl::Span<const int64_t> dimensions) : dimensions(dimensions), base(dimensions.size(), 0), step(dimensions.size(), 1) { if (!dimensions.empty()) { // Selects the shape with the largest minor dimension as the one upon // which to run the tight stride loop. if (dimensions[LayoutUtil::Minor(source_shape.layout(), 0)] >= dimensions[LayoutUtil::Minor(dest_shape.layout(), 0)]) { minor_dimension = LayoutUtil::Minor(source_shape.layout(), 0); dest_stride = IndexUtil::GetDimensionStride(dest_shape, minor_dimension); } else { minor_dimension = LayoutUtil::Minor(dest_shape.layout(), 0); source_stride = IndexUtil::GetDimensionStride(source_shape, minor_dimension); } minor_loop_size = dimensions[minor_dimension]; step[minor_dimension] = minor_loop_size; } } LiteralBase::~LiteralBase() = default; const Shape& LiteralBase::shape() const { return root_piece().subshape(); } const char* LiteralBase::Piece::buffer() const { // std::visit is avoided here due to its code size issues. if (auto* r = std::get_if<DenseRep>(&rep_)) { return r->data; } if (auto* r = std::get_if<DenseInlinedRep>(&rep_)) { return r->data; } DCHECK(std::holds_alternative<TupleRep>(rep_) || std::holds_alternative<Uninitialized>(rep_)); return nullptr; } const LiteralBase::Piece& LiteralBase::piece( const ShapeIndex& shape_index) const { const Piece* piece = &root_piece(); for (const auto i : shape_index) { DCHECK_GE(i, 0); DCHECK_LT(i, piece->children_size()); piece = &piece->child(i); } return *piece; } std::ostream& operator<<(std::ostream& out, const Literal& literal) { out << literal.ToString(); return out; } Shape* MutableLiteralBase::mutable_shape_do_not_use() { const Shape* const_shape = shape_.get(); if (!shape_.OwnsPtr()) { shape_ = MaybeOwningShapePtr(std::make_unique<Shape>(*shape_)); } Shape* shape = shape_.get_mutable(); if (shape != const_shape) { std::function<void(const Shape&, Piece*)> set_piece_shapes = [&set_piece_shapes](const Shape& shape, Piece* piece) { piece->set_subshape(&shape); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); set_piece_shapes(subshape, &piece->child(i)); } } }; set_piece_shapes(*shape, &mutable_root_piece()); } return shape; } [&set_piece_shapes](const Shape& shape, Piece* piece) { piece->set_subshape(&shape); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); set_piece_shapes(subshape, &piece->child(i)); } } }; Literal::Literal() : Literal(NilShape()) {} Literal::Literal(const Shape& shape) : Literal(shape, /*allocate_arrays=*/true) {} void Literal::SetShape(const Shape& shape) { Shape shape_storage; const Shape* shape_ptr = &shape; if (LayoutUtil::HasCustomElementSizeInBits(shape)) { shape_storage = shape; shape_storage.mutable_layout()->set_element_size_in_bits(0); shape_ptr = &shape_storage; } if (const Shape* intered_shape_ptr = TryInternShape(*shape_ptr)) { shape_ = intered_shape_ptr; } else { shape_ = std::make_unique<Shape>(*shape_ptr); } } void Literal::SetPiece(const Shape& shape, Piece* piece, bool allocate_arrays, ArrayValueState leaf_array_value_state) { if (shape.IsTuple()) { for (const Shape& subshape : shape.tuple_shapes()) { Piece child_piece; child_piece.set_subshape(&subshape); SetPiece(subshape, &child_piece, allocate_arrays, leaf_array_value_state); piece->emplace_back(std::move(child_piece)); } } else if (shape.IsArray()) { DCHECK(LayoutUtil::IsDenseArray(shape)) << "literal array storage is currently only supported for dense " "arrays: " << shape; piece->set_array_value_state(leaf_array_value_state); if (leaf_array_value_state == LiteralBase::ArrayValueState::kKnown && allocate_arrays) { piece->AllocateBuffers(); } } } Literal::Literal(const Shape& shape, bool allocate_arrays, ArrayValueState leaf_array_value_state) : MutableLiteralBase() { SetShape(shape); CHECK(leaf_array_value_state != ArrayValueState::kKnown || LayoutUtil::HasLayout(*shape_)); root_piece_.set_subshape(shape_.get()); CHECK(&root_piece_.subshape() == shape_.get()); SetPiece(*shape_, &root_piece_, allocate_arrays, leaf_array_value_state); } Literal::~Literal() { DeallocateBuffers(); } void Literal::DeallocateBuffers() { root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { piece->DeallocateBuffers(); }); } Literal::Literal(Literal&& other) : MutableLiteralBase() { *this = std::move(other); } Literal& Literal::operator=(Literal&& other) { DCHECK(&other.root_piece_.subshape() == other.shape_.get()); using std::swap; swap(shape_, other.shape_); swap(root_piece_, other.root_piece_); DCHECK(&root_piece_.subshape() == shape_.get()); return *this; } Literal LiteralBase::CreateFromShape(const Shape& shape) { Literal literal(shape); literal.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (piece->subshape().IsArray()) { memset(piece->untyped_data(), 0, piece->size_bytes_dense()); } }); return literal; } [&](const ShapeIndex& index, Piece* piece) { if (piece->subshape().IsArray()) { memset(piece->untyped_data(), 0, piece->size_bytes_dense()); } }); Literal LiteralBase::CreateFromShapeWithUnknownLeafArrays(const Shape& shape) { Literal literal(shape, /*allocate_arrays=*/false, ArrayValueState::kUnknown); return literal; } Literal LiteralBase::CreateFromShapeWithUndeterminedLeafArrays( const Shape& shape) { Literal literal(shape, /*allocate_arrays=*/false, ArrayValueState::kUndetermined); return literal; } int32_t LiteralBase::GetDynamicSize(int64_t dim_index) const { return GetDynamicSize(dim_index, {}); } int32_t LiteralBase::GetDynamicSize(int64_t dim_index, const ShapeIndex& shape_index) const { return piece(shape_index).GetDynamicSize(dim_index); } std::optional<int64_t> LiteralBase::GetFirstInteger() const { if (!primitive_util::IsIntegralType(shape().element_type())) { return std::nullopt; } return primitive_util::IntegralTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, void LiteralBase::BuildPieceSubtree(const Shape& shape, Piece* piece) { CHECK(shape.IsTuple()); for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); Piece child_piece; child_piece.set_subshape(&subshape); if (subshape.IsTuple()) { BuildPieceSubtree(subshape, &child_piece); } piece->emplace_back(std::move(child_piece)); } } absl::Status LiteralBase::SerializeToString(std::string* output) const { ShapeProto shape_proto = shape().ToProto(); TF_ASSIGN_OR_RETURN(int64_t size, ShapeUtil::SerializedSizeWithProto(shape(), shape_proto)); output->resize(size); return SerializeWithShapeProto(shape_proto, output->data()); } absl::StatusOr<std::string> LiteralBase::SerializeAsString() const { std::string result; TF_RETURN_IF_ERROR(SerializeToString(&result)); return std::move(result); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { void MutableLiteralBase::CopyElementFrom(const LiteralSlice& src_literal, absl::Span<const int64_t> src_index, absl::Span<const int64_t> dest_index) { DCHECK(LayoutUtil::IsDenseArray(shape())); DCHECK_EQ(shape().element_type(), src_literal.shape().element_type()); const int64_t src_linear_index = IndexUtil::MultidimensionalIndexToLinearIndex(src_literal.shape(), src_index); const int64_t dest_linear_index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), dest_index); const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); char* dest_address = static_cast<char*>(untyped_data()) + dest_linear_index * primitive_size; const char* source_address = static_cast<const char*>(src_literal.untyped_data()) + src_linear_index * primitive_size; if (dest_address != source_address) { memcpy(dest_address, source_address, primitive_size); } } /* static */ absl::StatusOr<Literal> MutableLiteralBase::CreateFromProto( const LiteralProto& proto, bool prohibit_empty_literal) { if (!proto.has_shape()) { return InvalidArgument("LiteralProto has no shape"); } Shape shape(proto.shape()); if (ShapeUtil::HasPrimitiveType(shape, OPAQUE_TYPE)) { return InvalidArgument( "Literal shape cannot include OPAQUE_TYPE sub-shape"); } if (!LayoutUtil::HasLayout(shape)) { return InvalidArgument("LiteralProto has no layout"); } if (LayoutUtil::IsSparseArray(shape)) { return Unimplemented("Sparse literals are not supported"); } TF_RETURN_IF_ERROR(ShapeUtil::ValidateShapeWithOptionalLayout(shape)); Literal literal(shape); TF_RETURN_IF_ERROR(literal.root_piece_.ForEachMutableSubpieceWithStatus( [&](const ShapeIndex& index, Piece* piece) -> absl::Status { const LiteralProto* proto_element = &proto; for (int64_t i : index) { CHECK(i < proto_element->tuple_literals_size()); proto_element = &proto_element->tuple_literals(i); } if (piece->subshape().IsTuple()) { if (proto_element->tuple_literals_size() != ShapeUtil::TupleElementCount(piece->subshape())) { return InvalidArgument( "Expected %d tuple elements in LiteralProto, has %d", ShapeUtil::TupleElementCount(piece->subshape()), proto_element->tuple_literals_size()); } return absl::OkStatus(); } if (piece->subshape().element_type() == TOKEN) { return absl::OkStatus(); } CHECK(piece->subshape().IsArray()); // When prohibit_empty_literal is false (allowing literal with no // values), only copy from proto if the literal proto has values. This // mode is used for a learned cost model. if (prohibit_empty_literal || LiteralProtoHasValues(*proto_element)) { TF_RETURN_IF_ERROR(piece->CopyFromProto(*proto_element)); } return absl::OkStatus(); })); return std::move(literal); } TF_RETURN_IF_ERROR(literal.root_piece_.ForEachMutableSubpieceWithStatus( Literal Literal::SubLiteral(ShapeIndexView shape_index) { if (!shape_index.empty()) { auto decomposed = this->DecomposeTuple(); return decomposed.at(shape_index.front()) .SubLiteral(shape_index.subspan(1)); } else { return std::move(*this); } } std::vector<Literal> Literal::DecomposeTuple() { CHECK(shape().IsTuple()); std::vector<Literal> elements; const auto tuple_element_count = ShapeUtil::TupleElementCount(shape()); elements.reserve(tuple_element_count); for (int i = 0; i < tuple_element_count; ++i) { elements.push_back(Literal(ShapeUtil::GetSubshape(shape(), {i}), /*allocate_arrays=*/false)); Literal& element = elements.back(); element.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* dest_piece) { if (dest_piece->subshape().IsTuple()) { return; } ShapeIndex src_index = {i}; for (int64_t j : index) { src_index.push_back(j); } Piece& src_piece = piece(src_index); // Move the respective buffer over to the element Literal. dest_piece->MoveDataFrom(src_piece); }); } // Set this literal to be nil-shaped. *this = Literal(); return elements; } [&](const ShapeIndex& index, Piece* dest_piece) { if (dest_piece->subshape().IsTuple()) { return; } ShapeIndex src_index = {i}; for (int64_t j : index) { src_index.push_back(j); } Piece& src_piece = piece(src_index); // Move the respective buffer over to the element Literal. dest_piece->MoveDataFrom(src_piece); }); void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } int32_t LiteralBase::Piece::GetDynamicSize(int64_t dim_index) const { CHECK(LayoutUtil::IsDenseArray(subshape())); if (!subshape_->is_dynamic_dimension(dim_index)) { // This is a static dimension, return size. return subshape_->dimensions(dim_index); } return dynamic_size_buffer()[dim_index]; } void LiteralBase::Piece::SetDynamicSize(int64_t dim_index, int32_t size) { CHECK(LayoutUtil::IsDenseArray(subshape())); CHECK(subshape_->is_dynamic_dimension(dim_index)); dynamic_size_buffer()[dim_index] = size; } void LiteralBase::Piece::AllocateBuffers() { const int64_t bytes = total_bytes_dense(); if (bytes > kMaxInlinedBytes) { CHECK_EQ(buffer(), nullptr); rep_.emplace<DenseRep>(); set_buffer( static_cast<char*>(tsl::port::AlignedMalloc(bytes, kMinimumAlignment))); } else { rep_.emplace<DenseInlinedRep>(); } } void LiteralBase::Piece::DeallocateBuffers() { if (auto* array_rep = GetDenseRep()) { tsl::port::AlignedFree(array_rep->data); rep_.emplace<Uninitialized>(); } } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } absl::Status LiteralBase::Piece::CopyFrom(const LiteralBase::Piece& src, bool only_dynamic_bound) { CHECK(subshape_ != nullptr); CHECK(src.subshape_ != nullptr); CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK(LayoutUtil::IsDenseArray(src.subshape())) << __func__ << " is only supported for dense arrays: " << src.subshape(); if (!only_dynamic_bound) { CHECK(ShapeUtil::Compatible(subshape(), src.subshape())); } if (src.array_value_state_ == ArrayValueState::kUnknown || src.array_value_state_ == ArrayValueState::kUndetermined) { if (array_value_state_ == ArrayValueState::kKnown) { DeallocateBuffers(); } array_value_state_ = src.array_value_state_; return absl::OkStatus(); } else { CHECK(src.array_value_state_ == ArrayValueState::kKnown); if (array_value_state_ == ArrayValueState::kUndetermined || array_value_state_ == ArrayValueState::kUnknown) { AllocateBuffers(); } array_value_state_ = src.array_value_state_; } if (ShapeUtil::Equal(subshape(), src.subshape())) { // If the layouts are equal it's faster just to memcpy. memcpy(buffer(), src.buffer(), src.size_bytes_dense()); } else { std::vector<int64_t> origin(subshape().rank(), 0); primitive_util::ArrayTypeSwitch<void>( [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, subshape().element_type()); } DCHECK_EQ(dynamic_size_buffer_bytes(), src.dynamic_size_buffer_bytes()); if (subshape().is_dynamic() && src.subshape().is_dynamic()) { memcpy(dynamic_size_buffer(), src.dynamic_size_buffer(), src.dynamic_size_buffer_bytes()); } return absl::OkStatus(); } [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, void MutableLiteralBase::SetDynamicSize(int64_t dim_index, int32_t size) { return SetDynamicSize(dim_index, {}, size); } void MutableLiteralBase::SetDynamicSize(int64_t dim_index, const ShapeIndex& shape_index, int32_t size) { Shape* subshape = ShapeUtil::GetMutableSubshape(mutable_shape_do_not_use(), shape_index); CHECK(LayoutUtil::IsDenseArray(*subshape)) << __func__ << " is only supported for dense arrays: " << *subshape; CHECK_GE(subshape->dimensions(dim_index), size); subshape->set_dynamic_dimension(dim_index, true); CHECK_EQ(&piece(shape_index).subshape(), subshape); piece(shape_index).SetDynamicSize(dim_index, size); } absl::Status MutableLiteralBase::CopyFrom(const LiteralSlice& src_literal, const ShapeIndex& dest_shape_index, const ShapeIndex& src_shape_index, bool only_dynamic_bound) { const Shape& dest_subshape = ShapeUtil::GetSubshape(shape(), dest_shape_index); const Shape& src_subshape = ShapeUtil::GetSubshape(src_literal.shape(), src_shape_index); if (only_dynamic_bound) { auto& bound_shape = dest_subshape.is_static() ? src_subshape : dest_subshape; auto& compact_shape = dest_subshape.is_static() ? dest_subshape : src_subshape; CHECK(ShapeUtil::DynamicShapeIsCompatible(compact_shape, bound_shape)) << compact_shape.ToString() << " vs " << bound_shape.ToString(); } else { if (!ShapeUtil::Compatible(dest_subshape, src_subshape)) { return InvalidArgument( "Destination subshape incompatible with source subshape: %s vs %s", ShapeUtil::HumanString(dest_subshape), ShapeUtil::HumanString(src_subshape)); } } return mutable_root_piece().ForEachMutableSubpieceWithStatus( [&](const ShapeIndex& index, Piece* piece) { if (!piece->subshape().IsArray()) { return absl::OkStatus(); } // Determine if this index is in the part of this literal that we want // to copy over from src_literal. bool in_subtree_to_copy = true; for (int i = 0; i < dest_shape_index.size(); ++i) { if (index[i] != dest_shape_index[i]) { in_subtree_to_copy = false; break; } } if (!in_subtree_to_copy) { return absl::OkStatus(); } // Construct the index of the corresponding piece in the source literal. ShapeIndex src_piece_index = src_shape_index; for (int64_t i = dest_shape_index.size(), end = index.size(); i < end; ++i) { src_piece_index.push_back(index[i]); } TF_RETURN_IF_ERROR( piece->CopyFrom(src_literal.piece(src_piece_index), /*only_dynamic_bound=*/only_dynamic_bound)); return absl::OkStatus(); }); } [&](const ShapeIndex& index, Piece* piece) { if (!piece->subshape().IsArray()) { return absl::OkStatus(); } // Determine if this index is in the part of this literal that we want // to copy over from src_literal. bool in_subtree_to_copy = true; for (int i = 0; i < dest_shape_index.size(); ++i) { if (index[i] != dest_shape_index[i]) { in_subtree_to_copy = false; break; } } if (!in_subtree_to_copy) { return absl::OkStatus(); } // Construct the index of the corresponding piece in the source literal. ShapeIndex src_piece_index = src_shape_index; for (int64_t i = dest_shape_index.size(), end = index.size(); i < end; ++i) { src_piece_index.push_back(index[i]); } TF_RETURN_IF_ERROR( piece->CopyFrom(src_literal.piece(src_piece_index), /*only_dynamic_bound=*/only_dynamic_bound)); return absl::OkStatus(); }); absl::Status Literal::MoveFrom(Literal&& src_literal, const ShapeIndex& dest_shape_index) { const Shape& dest_subshape = ShapeUtil::GetSubshape(shape(), dest_shape_index); if (!ShapeUtil::Equal(dest_subshape, src_literal.shape())) { return InvalidArgument( "Destination subshape not equal to source shape: %s vs %s", ShapeUtil::HumanString(dest_subshape), ShapeUtil::HumanString(src_literal.shape())); } src_literal.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& src_index, Piece* src_piece) { if (!src_piece->subshape().IsArray()) { return; } ShapeIndex dest_index = dest_shape_index; for (int64_t i : src_index) { dest_index.push_back(i); } Piece& dest_piece = piece(dest_index); dest_piece.DeallocateBuffers(); dest_piece.MoveDataFrom(*src_piece); }); src_literal.shape_ = MaybeOwningShapePtr(&NilShape()); src_literal.root_piece_ = Piece(); src_literal.root_piece_.set_subshape(src_literal.shape_.get()); return absl::OkStatus(); } [&](const ShapeIndex& src_index, Piece* src_piece) { if (!src_piece->subshape().IsArray()) { return; } ShapeIndex dest_index = dest_shape_index; for (int64_t i : src_index) { dest_index.push_back(i); } Piece& dest_piece = piece(dest_index); dest_piece.DeallocateBuffers(); dest_piece.MoveDataFrom(*src_piece); }); absl::Status MutableLiteralBase::CopySliceFrom( const LiteralSlice& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << shape(); TF_RET_CHECK(LayoutUtil::IsDenseArray(src_literal.shape())) << src_literal.shape(); TF_RET_CHECK(ShapeUtil::SameElementType(src_literal.shape(), shape())); TF_RET_CHECK(src_literal.shape().rank() == src_base.size()); TF_RET_CHECK(shape().rank() == dest_base.size()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, void MutableLiteralBase::PopulateR1(const tsl::core::Bitmap& values) { CHECK(shape().IsArray()); CHECK_EQ(shape().rank(), 1); CHECK_EQ(element_count(), values.bits()); CHECK_EQ(shape().element_type(), PRED); for (int64_t i = 0; i < static_cast<int64_t>(values.bits()); ++i) { Set({i}, values.get(i)); } } void MutableLiteralBase::PopulateInplaceInternal( absl::FunctionRef<void(void*, absl::Span<const int64_t>, int)> populator, bool parallel) { const Shape& this_shape = shape(); const int64_t rank = this_shape.rank(); DCHECK(LayoutUtil::IsDenseArray(this_shape)); char* const dest_base = static_cast<char*>(untyped_data()); if (rank > 0) { StrideConfig stride_config(this_shape, this_shape, this_shape.dimensions()); const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); const int64_t num_elements = ShapeUtil::ElementsIn(shape()); // If we are rank-1 and we are `parallel`, it is better to use a smaller // `step` than what `StrideConfig` does: stick the entire dimension in the // inner-most loop. if (parallel && this_shape.rank() == 1) { const int64_t thread_count = ShapeUtil::GetForEachIndexParallelThreadCount(); // Let's just divide up the array into small amounts per thread. stride_config.dest_stride = stride_config.minor_loop_size = num_elements > 32 ? std::max<int64_t>(num_elements / thread_count, 1) : num_elements; stride_config.step = {stride_config.minor_loop_size}; } auto init_function = [&](absl::Span<const int64_t> indexes, int thread_id) -> absl::StatusOr<bool> { const int64_t index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), indexes); DimensionVector minor_scan_indexes(rank, 0); std::copy(indexes.begin(), indexes.end(), minor_scan_indexes.begin()); char* dest_ptr = dest_base + index * primitive_size; char* const dest_end = dest_base + // This handles the case where minor_loop_size does not evenly divide // the most minor dimension. std::min(index + stride_config.minor_loop_size, num_elements) * primitive_size; while (dest_ptr < dest_end) { populator(dest_ptr, minor_scan_indexes, thread_id); ++minor_scan_indexes[stride_config.minor_dimension]; dest_ptr += primitive_size; } return true; }; if (parallel) { ShapeUtil::ForEachIndexParallel(this_shape, stride_config.base, stride_config.dimensions, stride_config.step, init_function); } else { ShapeUtil::ForEachIndex( this_shape, stride_config.base, stride_config.dimensions, stride_config.step, [&init_function]( absl::Span<const int64_t> indexes) -> absl::StatusOr<bool> { auto result_ignored = init_function(indexes, /*thread_id=*/-1); return true; }); } } else { // For scalars. populator(dest_base, {}, /*thread_id=*/-1); } } auto init_function = [&](absl::Span<const int64_t> indexes, int thread_id) -> absl::StatusOr<bool> { const int64_t index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), indexes); DimensionVector minor_scan_indexes(rank, 0); std::copy(indexes.begin(), indexes.end(), minor_scan_indexes.begin()); char* dest_ptr = dest_base + index * primitive_size; char* const dest_end = dest_base + // This handles the case where minor_loop_size does not evenly divide // the most minor dimension. std::min(index + stride_config.minor_loop_size, num_elements) * primitive_size; while (dest_ptr < dest_end) { populator(dest_ptr, minor_scan_indexes, thread_id); ++minor_scan_indexes[stride_config.minor_dimension]; dest_ptr += primitive_size; } return true; }; [&init_function]( absl::Span<const int64_t> indexes) -> absl::StatusOr<bool> { auto result_ignored = init_function(indexes, /*thread_id=*/-1); return true; }); absl::Status MutableLiteralBase::PopulateInplace( absl::FunctionRef<void(void*, absl::Span<const int64_t>)> populator) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); PopulateInplaceInternal( [&](void* dest, absl::Span<const int64_t> indexes, int /*thread_id*/) { return populator(dest, indexes); }, /*parallel=*/false); return absl::OkStatus(); } absl::Status MutableLiteralBase::PopulateInplaceParallel( absl::FunctionRef<void(void*, absl::Span<const int64_t>, int)> populator) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); PopulateInplaceInternal(populator, /*parallel=*/element_count() > 32); return absl::OkStatus(); } Literal LiteralBase::Relayout(const Layout& new_layout, const ShapeIndex& shape_index) const { // Create new shape with 'new_layout' set at the given shape index. Shape new_shape = shape(); Shape* subshape = ShapeUtil::GetMutableSubshape(&new_shape, shape_index); TF_CHECK_OK(LayoutUtil::ValidateLayoutForShape(new_layout, *subshape)); *subshape->mutable_layout() = new_layout; // LINT.IfChange // s4 literals are stored in uint8_t/int8_t, therefore element_size_in_bits // must be removed. if (subshape->layout().element_size_in_bits() == 4) { subshape->mutable_layout()->set_element_size_in_bits(0); } // LINT.ThenChange(//tensorflow/compiler/xla/types.h) Literal result(new_shape); TF_CHECK_OK(result.CopyFrom(*this)); return result; } Literal LiteralBase::Relayout(const Shape& shape_with_layout) const { CHECK(ShapeUtil::Compatible(shape_with_layout, shape())) << "Given shape_with_layout " << ShapeUtil::HumanString(shape_with_layout) << " not compatible with literal shape " << ShapeUtil::HumanString(shape()); Literal result = CreateFromShape(shape_with_layout); ShapeUtil::ForEachSubshape( result.shape(), [this, &result](const Shape& subshape, const ShapeIndex& index) { if (subshape.IsArray()) { TF_CHECK_OK(result.CopyFrom(*this, /*dest_shape_index=*/index, /*src_shape_index=*/index)); } }); return result; } [this, &result](const Shape& subshape, const ShapeIndex& index) { if (subshape.IsArray()) { TF_CHECK_OK(result.CopyFrom(*this, /*dest_shape_index=*/index, /*src_shape_index=*/index)); } }); Literal LiteralBase::ToBoundedDynamic(const Shape& bounded_shape) const { CHECK(bounded_shape.is_dynamic()); Literal result(bounded_shape); ShapeUtil::ForEachSubshape( shape(), [&](const Shape& subshape, const ShapeIndex& index) { if (!subshape.IsArray()) { return; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (bounded_shape.is_dynamic_dimension(i)) { result.SetDynamicSize(i, subshape.dimensions(i)); } } }); TF_CHECK_OK(result.CopyFrom(*this, {}, {}, /*only_dynamic_bound=*/true)); return result; } shape(), [&](const Shape& subshape, const ShapeIndex& index) { if (!subshape.IsArray()) { return; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (bounded_shape.is_dynamic_dimension(i)) { result.SetDynamicSize(i, subshape.dimensions(i)); } } }); Literal LiteralBase::ToStatic() const { // Create new shape with 'new_layout' set at the given shape index. Shape new_shape = shape(); ShapeUtil::ForEachMutableSubshape( &new_shape, [this](Shape* subshape, const ShapeIndex& index) { if (!subshape->IsArray()) { return; } for (int64_t i = 0; i < subshape->rank(); ++i) { // GetDynamicSize has a 32-bit return type and may truncate static // dimensions, so make sure to skip. if (!subshape->is_dynamic_dimension(i)) continue; subshape->set_dynamic_dimension(i, false); subshape->set_dimensions(i, GetDynamicSize(i, index)); } }); Literal result(new_shape); TF_CHECK_OK(result.CopyFrom(*this, {}, {}, /*only_dynamic_bound=*/true)); return result; } &new_shape, [this](Shape* subshape, const ShapeIndex& index) { if (!subshape->IsArray()) { return; } for (int64_t i = 0; i < subshape->rank(); ++i) { // GetDynamicSize has a 32-bit return type and may truncate static // dimensions, so make sure to skip. if (!subshape->is_dynamic_dimension(i)) continue; subshape->set_dynamic_dimension(i, false); subshape->set_dimensions(i, GetDynamicSize(i, index)); } }); absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { absl::StatusOr<Literal> LiteralBase::Broadcast( const Shape& result_shape, absl::Span<const int64_t> dimensions) const { const LiteralBase& src = *this; const Shape& src_shape = shape(); if (!src_shape.IsArray()) { return InvalidArgument("Broadcast only supports arrays."); } const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(src_shape.element_type()); switch (primitive_size) { case 0: return BroadcastHelper<0>(src, src_shape, result_shape, dimensions); case 1: return BroadcastHelper<1>(src, src_shape, result_shape, dimensions); case 2: return BroadcastHelper<2>(src, src_shape, result_shape, dimensions); case 4: return BroadcastHelper<4>(src, src_shape, result_shape, dimensions); case 8: return BroadcastHelper<8>(src, src_shape, result_shape, dimensions); case 16: return BroadcastHelper<16>(src, src_shape, result_shape, dimensions); default: LOG(FATAL) << "Unhandled primitive size " << primitive_size; return InvalidArgument("Unhandled primitive size"); break; } } absl::StatusOr<Literal> LiteralBase::Reshape( absl::Span<const int64_t> dimensions) const { if (!LayoutUtil::IsDenseArray(shape())) { return InvalidArgument("Reshape is only supported for dense arrays."); } if (shape().is_dynamic()) { // TODO(b/243182930): We should consider supporting dynamic reshape. return Unimplemented("Dynamic reshape is not implemented."); } Literal output; if (!LayoutUtil::IsMonotonicWithDim0Major(shape().layout())) { output = Relayout(LayoutUtil::GetDefaultLayoutForRank(shape().rank())); } else { output = Clone(); } // Because the layout is monotonic, we can simply reuse the same sequence of // values without changing their order. *output.mutable_shape_do_not_use() = ShapeUtil::MakeShape(shape().element_type(), dimensions); int64_t elements_before = ShapeUtil::ElementsIn(shape()); int64_t elements_after = ShapeUtil::ElementsIn(output.shape()); if (elements_before != elements_after) { return InvalidArgument( "Shapes before and after Literal::Reshape have different numbers " "of elements: %s vs %s.", ShapeUtil::HumanString(shape()), ShapeUtil::HumanString(output.shape())); } return std::move(output); } Literal LiteralBase::Transpose(absl::Span<const int64_t> permutation) const { CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); CHECK(shape().rank() == permutation.size() && IsPermutation(permutation)) << "Given permutation is not a permutation of dimension numbers"; // To transpose the array, we just permute the dimensions and layout, and // do a straight memory copy of the raw data set. // This is considerably faster than iterating over every array element using // the EachCell<>() and Set<>() APIs. Shape permuted_shape = ShapeUtil::PermuteDimensions(permutation, shape()); // Replace the layout with one affine to this shape, such that a // transpose operation can be performed by leaving the flat values // representation intact. // For example, consider the shape F32[11,8]{1,0} under a {1,0} permutation. // The shape with affine layout resulting from that operation will be // F32[8,11]{0,1}, since it leaves the original most minor (the 8 sized), the // most minor. // // Essentially, given MinMaj(Di) the position of the Di dimension within the // minor to major vector, and given T(Di) the index that the original Di // dimension has within the transposed array, a layout is affine if // MinMaj(Di) == TMinMaj(T(Di)), with TMinMaj() being the minor to major // vector of the affine layout. std::vector<int64_t> inverse_permutation = InversePermutation(permutation); CHECK(LayoutUtil::IsDenseArray(permuted_shape)); Layout* layout = permuted_shape.mutable_layout(); layout->clear_minor_to_major(); for (auto index : LayoutUtil::MinorToMajor(shape())) { layout->add_minor_to_major(inverse_permutation[index]); } Literal new_literal(permuted_shape); if (shape().is_dynamic()) { for (int64_t i = 0; i < shape().rank(); i++) { if (shape().is_dynamic_dimension(i)) { // Set the dynamic size of any dynamic dimension in the transposed // literal. new_literal.SetDynamicSize(inverse_permutation[i], GetDynamicSize(i)); } } } DCHECK_EQ(ShapeUtil::ByteSizeOf(new_literal.shape()), ShapeUtil::ByteSizeOf(shape())); std::memcpy(new_literal.untyped_data(), untyped_data(), size_bytes()); return new_literal; } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( Literal LiteralBase::Slice(absl::Span<const int64_t> start_indices, absl::Span<const int64_t> limit_indices) const { CHECK(shape().IsArray()) << "tuple is not supported for slice"; DimensionVector result_dimensions; for (int64_t dnum = 0; dnum < shape().rank(); ++dnum) { CHECK_GE(start_indices[dnum], 0); CHECK_LE(limit_indices[dnum], shape().dimensions(dnum)) << "dnum = " << dnum; int64_t dimension = limit_indices[dnum] - start_indices[dnum]; CHECK_GE(dimension, 0) << "dnum = " << dnum; result_dimensions.push_back(dimension); } auto result_shape = ShapeUtil::MakeShapeWithDenseLayout( shape().element_type(), result_dimensions, LayoutUtil::MinorToMajor(shape())); ShapeUtil::CopyDynamicDimensions(&result_shape, shape()); Literal result_literal(result_shape); primitive_util::ArrayTypeSwitch<void>( [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; return SliceInternal<NativeT>(*this, start_indices, result_literal); }, result_shape.element_type()); return result_literal; } Literal LiteralBase::Clone() const { Literal result(shape()); TF_CHECK_OK(result.CopyFrom(*this)); return result; } std::unique_ptr<Literal> LiteralBase::CloneToUnique() const { auto result = std::make_unique<Literal>(shape()); TF_CHECK_OK(result->CopyFrom(*this)); return result; } bool LiteralBase::IsDetermined(const ShapeIndex& shape_index) const { return piece(shape_index).IsDetermined(); } bool LiteralBase::IsKnown(const ShapeIndex& shape_index) const { return piece(shape_index).IsKnown(); } std::string LiteralBase::GetAsString(absl::Span<const int64_t> multi_index, const ShapeIndex& shape_index) const { const Shape& subshape = ShapeUtil::GetSubshape(shape(), shape_index); CHECK(LayoutUtil::IsDenseArray(subshape)); return primitive_util::ArrayTypeSwitch<std::string>( [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, subshape.element_type()); } [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, std::optional<int64_t> LiteralBase::GetIntegralAsS64( absl::Span<const int64_t> multi_index) const { CHECK(LayoutUtil::IsDenseArray(shape())); return primitive_util::PrimitiveTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, std::optional<double> LiteralBase::GetAsDouble( absl::Span<const int64_t> multi_index) const { const Shape& s = shape(); CHECK(LayoutUtil::IsDenseArray(s)); return primitive_util::PrimitiveTypeSwitch<std::optional<double>>( [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, s.element_type()); } [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, std::optional<double> LiteralBase::GetSumAsDouble( absl::Span<const int64_t> linear_indices) const { const Shape& s = shape(); CHECK(LayoutUtil::IsDenseArray(s)); if (!primitive_util::IsFloatingPointType(s.element_type())) { return std::nullopt; } return primitive_util::FloatingPointTypeSwitch<double>( [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, s.element_type()); } [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, std::optional<complex128> LiteralBase::GetAsComplex128( absl::Span<const int64_t> multi_index) const { return primitive_util::PrimitiveTypeSwitch<std::optional<complex128>>( [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, absl::Status MutableLiteralBase::SetIntegralAsS64( absl::Span<const int64_t> multi_index, int64_t value) { CHECK(LayoutUtil::IsDenseArray(shape())); return primitive_util::PrimitiveTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, absl::Status MutableLiteralBase::SetFromDouble( absl::Span<const int64_t> multi_index, double value) { CHECK(LayoutUtil::IsDenseArray(shape())); if (!primitive_util::IsFloatingPointType(shape().element_type())) { return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); } primitive_util::FloatingPointTypeSwitch<void>( [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, shape().element_type()); return absl::OkStatus(); } [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, void PrintShape(bool print_layout, const Shape& shape, Printer* printer) { if (print_layout) { ShapeUtil::PrintHumanStringWithLayout(printer, shape); } else { ShapeUtil::PrintHumanString(printer, shape); } } void TuplePrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); printer->Append(oneline ? "( " : "(\n"); for (int i = 0; i < ShapeUtil::TupleElementCount(subshape); ++i) { ShapeIndex element_index = shape_index; element_index.push_back(i); if (i > 0) printer->Append(oneline ? ", " : ",\n"); PrintHelper(literal, element_index, print_shape, print_layout, oneline, printer); } printer->Append(oneline ? " )" : "\n)"); } void DenseArrayPrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); int64_t rank = subshape.rank(); const absl::string_view linebreak = oneline ? " " : "\n"; std::function<void(absl::Span<const int64_t> dimensions, std::vector<int64_t>*)> print_recursive = [&](absl::Span<const int64_t> dimensions, std::vector<int64_t>* accum_indices) { // dimensions.size() decreases by 1 at each recursive call, // and accum_indices->size() increases by 1. // Their sum is equal to the rank of the tensor. CHECK_EQ(rank, dimensions.size() + accum_indices->size()); auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; if (dimensions.empty()) { // Display predicates as 0s and 1s so that the string is more dense. std::string elem; if (subshape.element_type() == PRED && rank > 0) { elem = literal.Get<bool>(*accum_indices, shape_index) ? "1" : "0"; } else { elem = literal.GetAsString(*accum_indices, shape_index); } printer->Append(elem); } else { printer->Append(brace_to_string("{")); for (int i = 0; i < dimensions[0]; ++i) { accum_indices->push_back(i); print_recursive(dimensions.subspan(1), accum_indices); accum_indices->pop_back(); if (i < dimensions[0] - 1) { printer->Append(","); printer->Append(dimensions.size() > 1 ? linebreak : " "); } } printer->Append(brace_to_string("}")); } }; if (print_shape) { PrintShape(print_layout, subshape, printer); if (subshape.is_dynamic()) { printer->Append("("); for (int64_t i = 0; i < subshape.dimensions_size(); ++i) { printer->Append(literal.GetDynamicSize(i, shape_index)); if (i < subshape.dimensions_size() - 1) { printer->Append(","); } } printer->Append(")"); } printer->Append(" "); } std::vector<int64_t> indices = {}; std::vector<int64_t> dimensions; dimensions.reserve(subshape.rank()); for (int64_t i = 0; i < subshape.rank(); ++i) { dimensions.push_back(literal.GetDynamicSize(i, shape_index)); } print_recursive(dimensions, &indices); } print_recursive = [&](absl::Span<const int64_t> dimensions, std::vector<int64_t>* accum_indices) { // dimensions.size() decreases by 1 at each recursive call, // and accum_indices->size() increases by 1. // Their sum is equal to the rank of the tensor. CHECK_EQ(rank, dimensions.size() + accum_indices->size()); auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; if (dimensions.empty()) { // Display predicates as 0s and 1s so that the string is more dense. std::string elem; if (subshape.element_type() == PRED && rank > 0) { elem = literal.Get<bool>(*accum_indices, shape_index) ? "1" : "0"; } else { elem = literal.GetAsString(*accum_indices, shape_index); } printer->Append(elem); } else { printer->Append(brace_to_string("{")); for (int i = 0; i < dimensions[0]; ++i) { accum_indices->push_back(i); print_recursive(dimensions.subspan(1), accum_indices); accum_indices->pop_back(); if (i < dimensions[0] - 1) { printer->Append(","); printer->Append(dimensions.size() > 1 ? linebreak : " "); } } printer->Append(brace_to_string("}")); } }; auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; void PrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); CHECK(LayoutUtil::HasLayout(literal.shape())); CHECK(LayoutUtil::HasLayout(subshape)); if (subshape.IsTuple()) { TuplePrintHelper(literal, shape_index, print_shape, print_layout, oneline, printer); } else if (subshape.IsToken()) { printer->Append("token"); } else { CHECK(LayoutUtil::IsDenseArray(subshape)); if (literal.IsKnown(shape_index)) { DenseArrayPrintHelper(literal, shape_index, print_shape, print_layout, oneline, printer); } else { PrintShape(print_layout, subshape, printer); printer->Append(" "); if (literal.IsDetermined(shape_index)) { printer->Append("unknown"); } else { printer->Append("undetermined"); } } } } void LiteralBase::Print(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/false, /*oneline=*/false, printer); } void LiteralBase::PrintOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/false, /*oneline=*/true, printer); } void LiteralBase::PrintWithoutShape(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/false, /*print_layout=*/false, /*oneline=*/false, printer); } void LiteralBase::PrintWithoutShapeOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/false, /*print_layout=*/false, /*oneline=*/true, printer); } void LiteralBase::PrintWithLayout(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/true, /*oneline=*/false, printer); } void LiteralBase::PrintWithLayoutOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/true, /*oneline=*/true, printer); } std::string LiteralBase::ToString() const { StringPrinter printer; Print(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringOneline() const { StringPrinter printer; PrintOneline(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithoutShape() const { StringPrinter printer; PrintWithoutShape(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithoutShapeOneline() const { StringPrinter printer; PrintWithoutShapeOneline(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithLayout() const { StringPrinter printer; PrintWithLayout(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithLayoutOneline() const { StringPrinter printer; PrintWithLayoutOneline(&printer); return std::move(printer).ToString(); } void LiteralBase::EachCellAsString( absl::FunctionRef<void(absl::Span<const int64_t> indices, const std::string& value)> per_cell) const { if (ShapeUtil::IsZeroElementArray(shape())) { return; } auto indices = IndexUtil::LinearIndexToMultidimensionalIndex( shape(), /*linear_index=*/0); do { per_cell(indices, GetAsString(indices)); } while (IndexUtil::BumpIndices(shape(), absl::MakeSpan(indices))); } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { absl::StatusOr<Literal> ConvertSwitch(const LiteralBase& literal, PrimitiveType primitive_dest_type) { TF_RET_CHECK(LayoutUtil::IsDenseArray(literal.shape())); if (literal.shape().element_type() == primitive_dest_type) { return literal.Clone(); } // Source Array type requirement is ensured by IsDenseArray before. if (!primitive_util::IsArrayType(primitive_dest_type) || !primitive_util::IsArrayType(literal.shape().element_type())) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(literal.shape().element_type()), PrimitiveType_Name(primitive_dest_type)); } // At this point, we know both src & dst are array types, while src is not // complex type, so we can allocate the result literal here to avoid // duplicating it N^2 times in the conversion implementation. Literal result( ShapeUtil::ChangeElementType(literal.shape(), primitive_dest_type)); TF_RETURN_IF_ERROR(primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { return ConvertIfDestTypeMatches<primitive_type_constant>(literal, result); }, literal.shape().element_type())); return result; } absl::StatusOr<Literal> LiteralBase::Convert( PrimitiveType primitive_dest_type) const { return ConvertSwitch(*this, primitive_dest_type); } absl::StatusOr<Literal> LiteralBase::BitcastConvert( const Shape& dest_shape) const { if (ShapeUtil::ByteSizeOf(dest_shape) != ShapeUtil::ByteSizeOf(shape())) { return InvalidArgument( "Can not bitcast-convert from shape %s to a shape of different size %s", shape().ToString(), dest_shape.ToString()); } if (dest_shape.IsTuple() || shape().IsTuple()) { return InvalidArgument( "bitcast-convert is not valid for tuple shapes %s->%s", shape().ToString(), dest_shape.ToString()); } if (shape().is_dynamic() || dest_shape.is_dynamic()) { return InvalidArgument( "bitcast-convert is not valid for dynamic shape %s->%s", shape().ToString(), dest_shape.ToString()); } Literal out(dest_shape); std::memcpy(out.root_piece_.buffer(), root_piece().buffer(), root_piece().size_bytes_dense()); // Perform the reshape on little endian encoding even on big endian machines. if constexpr (!kLittleEndian) { // Swap byte ordering as per the input data type. size_t input_elem_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); TF_RETURN_IF_ERROR(tsl::ByteSwapArray( const_cast<char*>(out.root_piece().buffer()), input_elem_size, out.root_piece().size_bytes_dense() / input_elem_size)); // Swap byte ordering as per the output data type. size_t output_elem_size = ShapeUtil::ByteSizeOfPrimitiveType(dest_shape.element_type()); TF_RETURN_IF_ERROR(tsl::ByteSwapArray( const_cast<char*>(out.root_piece().buffer()), output_elem_size, out.root_piece().size_bytes_dense() / output_elem_size)); } return out; } absl::StatusOr<Literal> LiteralBase::ConvertToShape( const Shape& dest_shape) const { if (!dest_shape.IsTuple()) { return Convert(dest_shape.element_type()); } std::vector<Literal> elements; const auto tuple_element_count = ShapeUtil::TupleElementCount(shape()); elements.reserve(tuple_element_count); for (int i = 0; i < tuple_element_count; ++i) { auto element = LiteralSlice(*this, {i}); TF_ASSIGN_OR_RETURN( auto new_element, element.ConvertToShape(ShapeUtil::GetSubshape(dest_shape, {i}))); elements.push_back(std::move(new_element)); } return MutableLiteralBase::MoveIntoTuple(absl::MakeSpan(elements)); } /* static */ Literal MutableLiteralBase::MoveIntoTuple( absl::Span<Literal> elements) { std::vector<const Shape*> element_shapes; element_shapes.reserve(elements.size()); for (const Literal& element : elements) { element_shapes.push_back(&element.shape()); } Literal literal(ShapeUtil::MakeTupleShapeWithPtrs(element_shapes), /*allocate_arrays=*/false); for (int i = 0, end = elements.size(); i < end; ++i) { TF_CHECK_OK( literal.MoveFrom(std::move(elements[i]), /*dest_shape_index=*/{i})); } return literal; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualDynamicSize( const LiteralBase::Piece& other) const { DCHECK(ShapeUtil::Compatible(subshape(), other.subshape())); if (subshape().is_static()) { return true; } for (int64_t i = 0; i < subshape().rank(); ++i) { if (GetDynamicSize(i) != other.GetDynamicSize(i)) { return false; } } return true; } bool LiteralBase::Piece::EqualElements(const LiteralBase::Piece& other) const { if (subshape().is_static() && ShapeUtil::Equal(subshape(), other.subshape()) && subshape().IsArray()) { CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(size_bytes_dense(), other.size_bytes_dense()); if (primitive_util::IsSubByteNonPredType(subshape().element_type())) { CHECK(!primitive_util::IsFloatingPointType(subshape().element_type())); auto one_array = buffer(); auto two_array = other.buffer(); const int bits_per_element = primitive_util::BitWidth(subshape().element_type()); const uint8_t mask = LsbMask<uint8_t>(bits_per_element); for (int64_t i = 0; i < size_bytes_dense(); ++i) { if ((one_array[i] & mask) != (two_array[i] & mask)) return false; } return true; } return memcmp(buffer(), other.buffer(), size_bytes_dense()) == 0; } std::vector<int64_t> multi_index; return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeSrcT = NativeTypeOf<primitive_type_constant>; return EqualElementsInternal<NativeSrcT>(other, &multi_index); }, subshape().element_type()); } bool LiteralBase::Equal(const LiteralBase& other, bool layout_sensitive) const { // Checking the structure of tuple literals. Checks for dense arrays are // performed below. if (!ShapeUtil::EqualStructure(shape(), other.shape())) { return false; } return root_piece().ForEachSubpieceWithBool([&](const ShapeIndex& index, const Piece& piece) { const Piece& other_piece = other.piece(index); const Shape& subshape = piece.subshape(); const Shape& other_subshape = other_piece.subshape(); if (subshape.element_type() != other_subshape.element_type()) { return false; } if (!piece.subshape().IsArray()) { return true; } if (subshape.rank() != other_subshape.rank()) { return false; } if (layout_sensitive && (subshape.layout() != other_subshape.layout())) { return false; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (piece.GetDynamicSize(i) != other_piece.GetDynamicSize(i)) { return false; } } if (!piece.EqualElements(other_piece)) { return false; } return true; }); } return root_piece().ForEachSubpieceWithBool([&](const ShapeIndex& index, const Piece& piece) { const Piece& other_piece = other.piece(index); const Shape& subshape = piece.subshape(); const Shape& other_subshape = other_piece.subshape(); if (subshape.element_type() != other_subshape.element_type()) { return false; } if (!piece.subshape().IsArray()) { return true; } if (subshape.rank() != other_subshape.rank()) { return false; } if (layout_sensitive && (subshape.layout() != other_subshape.layout())) { return false; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (piece.GetDynamicSize(i) != other_piece.GetDynamicSize(i)) { return false; } } if (!piece.EqualElements(other_piece)) { return false; } return true; }); static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(std::complex<T> a, std::complex<T> b) { return EqualIncludingNan(a.real(), b.real()) && EqualIncludingNan(a.imag(), b.imag()); } static bool EqualIncludingNan(std::complex<T> a, std::complex<T> b) { return EqualIncludingNan(a.real(), b.real()) && EqualIncludingNan(a.imag(), b.imag()); } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } bool Literal::Piece::IsAll(const Literal& scalar) const { CHECK(ShapeUtil::IsScalar(scalar.shape())) << scalar.shape().ToString(); if (!subshape().IsArray()) { return false; } CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(subshape().element_type(), scalar.shape().element_type()); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, subshape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, int64_t Literal::Piece::CountAll(const Literal& scalar) const { CHECK(ShapeUtil::IsScalar(scalar.shape())) << scalar.shape().ToString(); if (!subshape().IsArray()) { return 0; } CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(subshape().element_type(), scalar.shape().element_type()); return primitive_util::ArrayTypeSwitch<int64_t>( [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, subshape().element_type()); } [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { bool LiteralBase::IsAll(const Literal& scalar) const { return root_piece().IsAll(scalar); } bool LiteralBase::IsAll(int8_t value) const { if (!shape().IsArray()) { return false; } PrimitiveType ty = shape().element_type(); if (primitive_util::IsFloatingPointType(ty)) { return IsAllFloatImpl(value, /*round_value=*/false); } if (primitive_util::IsUnsignedIntegralType(ty) && value < 0) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllFloat(float value) const { return IsAllFloatImpl(value, /*round_value=*/true); } bool LiteralBase::IsAllFloatImpl(float value, bool round_value) const { PrimitiveType ty = shape().element_type(); if (!primitive_util::IsFloatingPointType(ty)) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::FloatingPointTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllComplex(complex64 value) const { PrimitiveType ty = shape().element_type(); if (!primitive_util::IsComplexType(ty)) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::ComplexTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllFirst() const { if (!shape().IsArray()) { return false; } // Empty shapes are not all the first element since there is no first element. if (ShapeUtil::IsZeroElementArray(shape())) { return false; } absl::InlinedVector<int64_t, 4> start_indices(/*n=*/shape().rank(), 0); absl::InlinedVector<int64_t, 4> end_indices(/*n=*/shape().rank(), 1); Literal first = Slice(start_indices, end_indices); return IsAll(first.Reshape({}).value()); } bool LiteralBase::IsR1Iota() const { if (!shape().IsArray()) { return false; } CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); if (shape().rank() != 1) { return false; } return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, shape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, std::optional<int64_t> LiteralBase::IsR1StridedIota() const { if (!shape().IsArray() || shape().rank() != 1) { return std::nullopt; } CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); const int64_t elements = ShapeUtil::ElementsIn(shape()); const PrimitiveType type = shape().element_type(); if (elements <= 1 || !primitive_util::IsIntegralType(type)) { return std::nullopt; } return primitive_util::IntegralTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, bool LiteralBase::IsZero(absl::Span<const int64_t> indices) const { CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, shape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void LiteralBase::Piece::set_array_value_state(ArrayValueState state) { array_value_state_ = state; } LiteralBase::ArrayValueState LiteralBase::Piece::get_array_value_state() const { return array_value_state_; } void LiteralBase::Piece::WriteToProto(LiteralProto* proto) const { *proto->mutable_shape() = subshape().ToProto(); switch (subshape().element_type()) { case PRED: CopyToRepeatedField(proto->mutable_preds(), data<bool>()); break; case U2: *proto->mutable_u2s() = std::string( reinterpret_cast<const char*>(data<u2>().data()), size_bytes_dense()); break; case U4: *proto->mutable_u4s() = std::string( reinterpret_cast<const char*>(data<u4>().data()), size_bytes_dense()); break; case U8: proto->set_u8s(static_cast<const unsigned char*>(data<uint8_t>().data()), element_count()); break; case U16: *proto->mutable_u16s() = std::string(reinterpret_cast<const char*>(data<uint16_t>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_u16s()); } break; case U32: CopyToRepeatedField(proto->mutable_u32s(), data<uint32_t>()); break; case U64: CopyToRepeatedField(proto->mutable_u64s(), data<uint64_t>()); break; case S2: *proto->mutable_s2s() = std::string( reinterpret_cast<const char*>(data<s2>().data()), size_bytes_dense()); break; case S4: *proto->mutable_s4s() = std::string( reinterpret_cast<const char*>(data<s4>().data()), size_bytes_dense()); break; case S8: proto->set_s8s(static_cast<const signed char*>(data<int8_t>().data()), element_count()); break; case S16: *proto->mutable_s16s() = std::string(reinterpret_cast<const char*>(data<int16_t>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_s16s()); } break; case S32: CopyToRepeatedField(proto->mutable_s32s(), data<int32_t>()); break; case S64: CopyToRepeatedField(proto->mutable_s64s(), data<int64_t>()); break; case F8E5M2: *proto->mutable_f8e5m2s() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e5m2>().data()), size_bytes_dense()); break; case F8E4M3FN: *proto->mutable_f8e4m3fns() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3fn>().data()), size_bytes_dense()); break; case F8E4M3B11FNUZ: *proto->mutable_f8e4m3b11fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3b11fnuz>().data()), size_bytes_dense()); break; case F8E5M2FNUZ: *proto->mutable_f8e5m2fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e5m2fnuz>().data()), size_bytes_dense()); break; case F8E4M3FNUZ: *proto->mutable_f8e4m3fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3fnuz>().data()), size_bytes_dense()); break; case F16: *proto->mutable_f16s() = std::string(reinterpret_cast<const char*>(data<half>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_f16s()); } break; case BF16: *proto->mutable_bf16s() = std::string(reinterpret_cast<const char*>(data<bfloat16>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_bf16s()); } break; case F32: CopyToRepeatedField(proto->mutable_f32s(), data<float>()); break; case F64: CopyToRepeatedField(proto->mutable_f64s(), data<double>()); break; case C64: for (complex64 value : data<complex64>()) { proto->add_c64s(value.real()); proto->add_c64s(value.imag()); } break; case C128: for (complex128 value : data<complex128>()) { proto->add_c128s(value.real()); proto->add_c128s(value.imag()); } break; case TUPLE: case TOKEN: // Nothing to do but assign the shape which is done above. return; default: // TODO(b/111551621): Support serializing more PrimitiveTypes. LOG(FATAL) << "Unhandled primitive type " << PrimitiveType_Name(subshape().element_type()); } } const void* LiteralBase::Piece::untyped_data() const { DCHECK(LayoutUtil::IsDenseArray(subshape())) << ShapeUtil::HumanString(subshape()); return buffer(); } void* LiteralBase::Piece::untyped_data() { DCHECK(LayoutUtil::IsDenseArray(subshape())) << ShapeUtil::HumanString(subshape()); return buffer(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status LiteralBase::Piece::CopyFromProto(const LiteralProto& proto) { // These conditions should have been checked in // MutableLiteralBase::CreateFromProto. TF_RET_CHECK(proto.has_shape()); Shape shape(proto.shape()); TF_RET_CHECK(LayoutUtil::HasLayout(shape)); TF_RET_CHECK(ShapeUtil::Equal(shape, subshape())); switch (subshape().element_type()) { case PRED: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<bool>(), proto.preds())); break; case S2: { const std::string& s(proto.s2s()); TF_RET_CHECK(data<s2>().size() * sizeof(s2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case S4: { const std::string& s(proto.s4s()); TF_RET_CHECK(data<s4>().size() * sizeof(s4) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case S8: { auto s8_data = data<int8_t>(); TF_RET_CHECK(proto.s8s().size() == s8_data.size()); std::copy(proto.s8s().begin(), proto.s8s().end(), s8_data.begin()); break; } case S16: { const std::string& s(proto.s16s()); TF_RET_CHECK(data<int16_t>().size() * sizeof(int16_t) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case S32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<int32_t>(), proto.s32s())); break; case S64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<int64_t>(), proto.s64s())); break; case U2: { const std::string& s(proto.u2s()); TF_RET_CHECK(data<u2>().size() * sizeof(u2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case U4: { const std::string& s(proto.u4s()); TF_RET_CHECK(data<u4>().size() * sizeof(u4) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case U8: { auto u8_data = data<uint8_t>(); TF_RET_CHECK(proto.u8s().size() == u8_data.size()); std::copy(proto.u8s().begin(), proto.u8s().end(), u8_data.begin()); break; } case U16: { const std::string& s(proto.u16s()); TF_RET_CHECK(data<uint16_t>().size() * sizeof(uint16_t) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case U32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<uint32_t>(), proto.u32s())); break; case U64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<uint64_t>(), proto.u64s())); break; case F8E5M2: { const std::string& s(proto.f8e5m2s()); TF_RET_CHECK(data<tsl::float8_e5m2>().size() * sizeof(tsl::float8_e5m2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3FN: { const std::string& s(proto.f8e4m3fns()); TF_RET_CHECK(data<tsl::float8_e4m3fn>().size() * sizeof(tsl::float8_e4m3fn) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3B11FNUZ: { const std::string& s(proto.f8e4m3b11fnuzs()); TF_RET_CHECK(data<tsl::float8_e4m3b11fnuz>().size() * sizeof(tsl::float8_e4m3b11fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E5M2FNUZ: { const std::string& s(proto.f8e5m2fnuzs()); TF_RET_CHECK(data<tsl::float8_e5m2fnuz>().size() * sizeof(tsl::float8_e5m2fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3FNUZ: { const std::string& s(proto.f8e4m3fnuzs()); TF_RET_CHECK(data<tsl::float8_e4m3fnuz>().size() * sizeof(tsl::float8_e4m3fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F16: { const std::string& s(proto.f16s()); TF_RET_CHECK(data<half>().size() * sizeof(half) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case BF16: { const std::string& s(proto.bf16s()); TF_RET_CHECK(data<bfloat16>().size() * sizeof(bfloat16) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case F32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<float>(), proto.f32s())); break; case F64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<double>(), proto.f64s())); break; case C64: { auto complex_data = data<complex64>(); TF_RET_CHECK(proto.c64s_size() == complex_data.size() * 2); for (int64_t i = 0; i < complex_data.size(); ++i) { complex_data[i] = complex64{proto.c64s(i * 2), proto.c64s(i * 2 + 1)}; } break; } case C128: { auto complex_data = data<complex128>(); const int64_t complex_data_size_doubled = complex_data.size() * 2; TF_RET_CHECK(proto.c128s_size() == complex_data_size_doubled); for (int64_t i = 0, end = complex_data.size(); i < end; ++i) { complex_data[i] = complex128{proto.c128s(i * 2), proto.c128s(i * 2 + 1)}; } break; } case TUPLE: return InvalidArgument("Should not be called on tuple shapes: %s", ShapeUtil::HumanString(subshape())); default: return InvalidArgument("Is called on unsupported shape: %s", ShapeUtil::HumanString(subshape())); } return absl::OkStatus(); } bool LiteralBase::Piece::IsKnown() const { if (array_value_state_ != ArrayValueState::kKnown) { return false; } if (subshape().IsTuple()) { bool are_all_leaf_arrays_known = true; ForEachSubpiece([&are_all_leaf_arrays_known](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_known &= piece.IsKnown(); }); return are_all_leaf_arrays_known; } return true; } ForEachSubpiece([&are_all_leaf_arrays_known](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_known &= piece.IsKnown(); }); bool LiteralBase::Piece::IsDetermined() const { if (array_value_state_ == ArrayValueState::kUndetermined) { return false; } if (subshape().IsTuple()) { bool are_all_leaf_arrays_determined = true; ForEachSubpiece([&are_all_leaf_arrays_determined](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_determined &= piece.IsDetermined(); }); return are_all_leaf_arrays_determined; } return true; } ForEachSubpiece([&are_all_leaf_arrays_determined](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_determined &= piece.IsDetermined(); }); LiteralProto LiteralBase::ToProto() const { LiteralProto proto; root_piece().ForEachSubpiece( [&](const ShapeIndex& index, const Piece& piece) { LiteralProto* proto_piece = &proto; for (int64_t i : index) { while (proto_piece->tuple_literals_size() <= i) { proto_piece->add_tuple_literals(); } proto_piece = proto_piece->mutable_tuple_literals(i); } piece.WriteToProto(proto_piece); }); return proto; } [&](const ShapeIndex& index, const Piece& piece) { LiteralProto* proto_piece = &proto; for (int64_t i : index) { while (proto_piece->tuple_literals_size() <= i) { proto_piece->add_tuple_literals(); } proto_piece = proto_piece->mutable_tuple_literals(i); } piece.WriteToProto(proto_piece); }); const void* LiteralBase::untyped_data(const ShapeIndex& shape_index) const { return piece(shape_index).untyped_data(); } void* MutableLiteralBase::untyped_data(const ShapeIndex& shape_index) { return piece(shape_index).untyped_data(); } int64_t LiteralBase::size_bytes(const ShapeIndex& shape_index) const { return piece(shape_index).size_bytes_dense(); } std::string LiteralBase::GetR1U8AsString() const { CHECK(shape().IsArray()); CHECK_EQ(shape().rank(), 1); CHECK_EQ(shape().element_type(), U8); return std::string(absl::bit_cast<const char*>(data<uint8_t>().data()), ShapeUtil::ElementsIn(shape())); } void MutableBorrowingLiteral::CopyPieceSubtree(const Shape& shape, const Piece* src_piece, Piece* dest_piece) { DCHECK(ShapeUtil::Equal(src_piece->subshape(), dest_piece->subshape())) << "src_piece has shape: " << ShapeUtil::HumanString(src_piece->subshape()) << "dest_piece has shape: " << ShapeUtil::HumanString(dest_piece->subshape()); dest_piece->set_array_value_state(src_piece->get_array_value_state()); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); Piece child_piece; child_piece.set_subshape(&subshape); CopyPieceSubtree(subshape, &src_piece->child(i), &child_piece); dest_piece->emplace_back(std::move(child_piece)); } } else if (shape.IsArray()) { dest_piece->set_buffer(const_cast<char*>(src_piece->buffer())); } } MutableLiteralBase::~MutableLiteralBase() = default; MutableBorrowingLiteral::MutableBorrowingLiteral( const MutableBorrowingLiteral& literal) : MutableLiteralBase() { shape_ = literal.shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.root_piece(), root_piece_); } MutableBorrowingLiteral& MutableBorrowingLiteral::operator=( const MutableBorrowingLiteral& literal) { shape_ = literal.shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.root_piece(), root_piece_); return *this; } MutableBorrowingLiteral::MutableBorrowingLiteral(MutableLiteralBase* literal) : MutableLiteralBase() { shape_ = literal->shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal->root_piece(), root_piece_); } MutableBorrowingLiteral::MutableBorrowingLiteral( MutableBorrowingLiteral literal, const ShapeIndex& view_root) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(literal.piece(view_root).subshape()); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.piece(view_root), root_piece_); } MutableBorrowingLiteral::MutableBorrowingLiteral(const char* src_buf_ptr, const Shape& shape) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(shape); CHECK(LayoutUtil::HasLayout(*shape_)); CHECK(!shape_->IsTuple()); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); root_piece_->set_buffer(const_cast<char*>(src_buf_ptr)); } MutableBorrowingLiteral::MutableBorrowingLiteral(absl::Span<char*> src_buf_ptrs, const Shape& shape) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(shape); if (!shape_->IsTuple()) { CHECK_EQ(src_buf_ptrs.size(), 1); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); root_piece_->set_buffer(const_cast<char*>(src_buf_ptrs[0])); } else { CHECK(!ShapeUtil::IsNestedTuple(*shape_)); CHECK_EQ(src_buf_ptrs.size(), ShapeUtil::TupleElementCount(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); for (int i = 0; i < src_buf_ptrs.size(); ++i) { Piece child_piece; const auto& src_shape = shape_->tuple_shapes(i); CHECK(src_shape.IsArray()); child_piece.set_subshape(&src_shape); child_piece.set_buffer(src_buf_ptrs[i]); root_piece_->emplace_back(std::move(child_piece)); } } } MutableBorrowingLiteral::MutableBorrowingLiteral(ShapeTree<char*> src_buf_ptrs) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(src_buf_ptrs.shape()); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); BuildPieceSubtree(*shape_, root_piece_); root_piece_->ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); } [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); MutableBorrowingLiteral::~MutableBorrowingLiteral() { if (root_piece_ != nullptr) { delete root_piece_; } } LiteralSlice::LiteralSlice(const LiteralBase& literal) : LiteralBase(), root_piece_(&literal.root_piece()) {} LiteralSlice::LiteralSlice(const LiteralBase& literal, const ShapeIndex& view_root) : LiteralBase(), root_piece_(&literal.piece(view_root)) {} BorrowingLiteral::BorrowingLiteral(const char* src_buf_ptr, const Shape& shape) : LiteralBase(), shape_(std::make_unique<Shape>(shape)) { CHECK(shape_->IsArray()); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); root_piece_.set_buffer(const_cast<char*>(src_buf_ptr)); } BorrowingLiteral::BorrowingLiteral(absl::Span<const char* const> src_buf_ptrs, const Shape& shape) : LiteralBase(), shape_(std::make_unique<Shape>(shape)) { CHECK(shape_->IsTuple()); CHECK(!ShapeUtil::IsNestedTuple(*shape_)); CHECK_EQ(src_buf_ptrs.size(), ShapeUtil::TupleElementCount(*shape_)); root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); BuildPieceSubtree(*shape_, &root_piece_); for (int i = 0, end = src_buf_ptrs.size(); i < end; ++i) { const auto& src_shape = shape_->tuple_shapes(i); CHECK(src_shape.IsArray()); root_piece_.child(i).set_buffer(const_cast<char*>(src_buf_ptrs[i])); } } BorrowingLiteral::BorrowingLiteral(ShapeTree<const char*> src_buf_ptrs) : LiteralBase(), shape_(std::make_unique<Shape>(src_buf_ptrs.shape())) { root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); BuildPieceSubtree(*shape_, &root_piece_); root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); } [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); });
#include "xla/literal.h" #include <algorithm> #include <cmath> #include <complex> #include <cstdint> #include <functional> #include <limits> #include <random> #include <string> #include <tuple> #include <utility> #include <vector> #include "absl/base/casts.h" #include "absl/hash/hash.h" #include "absl/random/random.h" #include "absl/status/status.h" #include "absl/strings/match.h" #include "absl/types/span.h" #include "xla/array.h" #include "xla/array2d.h" #include "xla/array3d.h" #include "xla/array4d.h" #include "xla/index_util.h" #include "xla/layout.h" #include "xla/layout_util.h" #include "xla/literal_util.h" #include "xla/primitive_util.h" #include "xla/shape.h" #include "xla/shape_tree.h" #include "xla/shape_util.h" #include "xla/test.h" #include "xla/types.h" #include "xla/util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/errors.h" #include "tsl/platform/logging.h" // IWYU pragma: keep #include "tsl/platform/macros.h" #include "tsl/platform/ml_dtypes.h" #include "tsl/platform/statusor.h" #include "tsl/platform/test_benchmark.h" class LiteralUtilTest : public ::testing::Test { protected: LiteralUtilTest() { Array4D<float> arr4d({ // clang-format off { // i0=0 { // i1=0 {1, 2, 3}, // i2=0 {4, 5, 6}, // i2=1 {7, 8, 9}, // i2=2 }, { // i1=1 {11, 12, 13}, {14, 15, 16}, {17, 18, 19}, }, }, { // i0=1 { // i1=0 {101, 102, 103}, {104, 105, 106}, {107, 108, 109}, }, { // i1=1 {201, 202, 203}, // i2=0 {204, 205, 206}, // i2=1 {207, 208, 209}, // i2=2 }, }, // clang-format on }); layout_r2_dim0major_ = LayoutUtil::MakeLayout({1, 0}); layout_r2_dim0minor_ = LayoutUtil::MakeLayout({0, 1}); layout_r3_dim0major_ = LayoutUtil::MakeLayout({2, 1, 0}); layout_r3_dim0minor_ = LayoutUtil::MakeLayout({0, 1, 2}); layout_r4_dim0major_ = LayoutUtil::MakeLayout({3, 2, 1, 0}); layout_r4_dim0minor_ = LayoutUtil::MakeLayout({0, 1, 2, 3}); literal_r4_2x2x3x3_dim0major_ = LiteralUtil::CreateR4FromArray4DWithLayout<float>(arr4d, layout_r4_dim0major_); literal_r4_2x2x3x3_dim0minor_ = LiteralUtil::CreateR4FromArray4DWithLayout<float>(arr4d, layout_r4_dim0minor_); } Layout layout_r2_dim0major_; Layout layout_r2_dim0minor_; Layout layout_r3_dim0major_; Layout layout_r3_dim0minor_; Layout layout_r4_dim0major_; Layout layout_r4_dim0minor_; Literal literal_r4_2x2x3x3_dim0major_; Literal literal_r4_2x2x3x3_dim0minor_; }; TEST_F(LiteralUtilTest, BroadcastScalarToMatrix) { Literal literal = LiteralUtil::CreateR0<int32_t>(9); TF_ASSERT_OK_AND_ASSIGN( Literal broadcasted_literal, literal.Broadcast(/*result_shape=*/ShapeUtil::MakeShape(S32, {2, 2}), /*dimensions=*/{})); EXPECT_EQ(broadcasted_literal, LiteralUtil::CreateR2<int32_t>({{9, 9}, {9, 9}})); }
LiteralUtilTest_BroadcastVectorToMatrix0
xla/literal_test.cc
bool LiteralProtoHasValues(const LiteralProto& proto) { return !proto.s2s().empty() || !proto.s4s().empty() || !proto.s8s().empty() || !proto.s16s().empty() || proto.s32s_size() || proto.s64s_size() || !proto.u2s().empty() || !proto.u4s().empty() || !proto.u8s().empty() || !proto.u16s().empty() || proto.u32s_size() || proto.u64s_size() || !proto.f8e5m2s().empty() || !proto.f8e4m3fns().empty() || !proto.f8e4m3b11fnuzs().empty() || !proto.f8e5m2fnuzs().empty() || !proto.f8e4m3fnuzs().empty() || !proto.f16s().empty() || !proto.bf16s().empty() || proto.f32s_size() || proto.f64s_size() || proto.c64s_size() || proto.c128s_size() || proto.preds_size() || proto.tuple_literals_size(); } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { const Shape& NilShape() { static const Shape* shape = new Shape(TUPLE, {}, {}, {}); return *shape; } const Shape* TryInternShape(const Shape& shape) { if (shape.IsTuple() && shape.tuple_shapes_size() == 0) { return &NilShape(); } if (shape.IsArray() && shape.dimensions_size() == 0 && shape.is_static() && shape.layout().tiles_size() == 0 && shape.layout().memory_space() == 0) { return &ScalarShape(shape.element_type()); } return nullptr; } StrideConfig::StrideConfig(const Shape& source_shape, const Shape& dest_shape, absl::Span<const int64_t> dimensions) : dimensions(dimensions), base(dimensions.size(), 0), step(dimensions.size(), 1) { if (!dimensions.empty()) { // Selects the shape with the largest minor dimension as the one upon // which to run the tight stride loop. if (dimensions[LayoutUtil::Minor(source_shape.layout(), 0)] >= dimensions[LayoutUtil::Minor(dest_shape.layout(), 0)]) { minor_dimension = LayoutUtil::Minor(source_shape.layout(), 0); dest_stride = IndexUtil::GetDimensionStride(dest_shape, minor_dimension); } else { minor_dimension = LayoutUtil::Minor(dest_shape.layout(), 0); source_stride = IndexUtil::GetDimensionStride(source_shape, minor_dimension); } minor_loop_size = dimensions[minor_dimension]; step[minor_dimension] = minor_loop_size; } } LiteralBase::~LiteralBase() = default; const Shape& LiteralBase::shape() const { return root_piece().subshape(); } const char* LiteralBase::Piece::buffer() const { // std::visit is avoided here due to its code size issues. if (auto* r = std::get_if<DenseRep>(&rep_)) { return r->data; } if (auto* r = std::get_if<DenseInlinedRep>(&rep_)) { return r->data; } DCHECK(std::holds_alternative<TupleRep>(rep_) || std::holds_alternative<Uninitialized>(rep_)); return nullptr; } const LiteralBase::Piece& LiteralBase::piece( const ShapeIndex& shape_index) const { const Piece* piece = &root_piece(); for (const auto i : shape_index) { DCHECK_GE(i, 0); DCHECK_LT(i, piece->children_size()); piece = &piece->child(i); } return *piece; } std::ostream& operator<<(std::ostream& out, const Literal& literal) { out << literal.ToString(); return out; } Shape* MutableLiteralBase::mutable_shape_do_not_use() { const Shape* const_shape = shape_.get(); if (!shape_.OwnsPtr()) { shape_ = MaybeOwningShapePtr(std::make_unique<Shape>(*shape_)); } Shape* shape = shape_.get_mutable(); if (shape != const_shape) { std::function<void(const Shape&, Piece*)> set_piece_shapes = [&set_piece_shapes](const Shape& shape, Piece* piece) { piece->set_subshape(&shape); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); set_piece_shapes(subshape, &piece->child(i)); } } }; set_piece_shapes(*shape, &mutable_root_piece()); } return shape; } [&set_piece_shapes](const Shape& shape, Piece* piece) { piece->set_subshape(&shape); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); set_piece_shapes(subshape, &piece->child(i)); } } }; Literal::Literal() : Literal(NilShape()) {} Literal::Literal(const Shape& shape) : Literal(shape, /*allocate_arrays=*/true) {} void Literal::SetShape(const Shape& shape) { Shape shape_storage; const Shape* shape_ptr = &shape; if (LayoutUtil::HasCustomElementSizeInBits(shape)) { shape_storage = shape; shape_storage.mutable_layout()->set_element_size_in_bits(0); shape_ptr = &shape_storage; } if (const Shape* intered_shape_ptr = TryInternShape(*shape_ptr)) { shape_ = intered_shape_ptr; } else { shape_ = std::make_unique<Shape>(*shape_ptr); } } void Literal::SetPiece(const Shape& shape, Piece* piece, bool allocate_arrays, ArrayValueState leaf_array_value_state) { if (shape.IsTuple()) { for (const Shape& subshape : shape.tuple_shapes()) { Piece child_piece; child_piece.set_subshape(&subshape); SetPiece(subshape, &child_piece, allocate_arrays, leaf_array_value_state); piece->emplace_back(std::move(child_piece)); } } else if (shape.IsArray()) { DCHECK(LayoutUtil::IsDenseArray(shape)) << "literal array storage is currently only supported for dense " "arrays: " << shape; piece->set_array_value_state(leaf_array_value_state); if (leaf_array_value_state == LiteralBase::ArrayValueState::kKnown && allocate_arrays) { piece->AllocateBuffers(); } } } Literal::Literal(const Shape& shape, bool allocate_arrays, ArrayValueState leaf_array_value_state) : MutableLiteralBase() { SetShape(shape); CHECK(leaf_array_value_state != ArrayValueState::kKnown || LayoutUtil::HasLayout(*shape_)); root_piece_.set_subshape(shape_.get()); CHECK(&root_piece_.subshape() == shape_.get()); SetPiece(*shape_, &root_piece_, allocate_arrays, leaf_array_value_state); } Literal::~Literal() { DeallocateBuffers(); } void Literal::DeallocateBuffers() { root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { piece->DeallocateBuffers(); }); } Literal::Literal(Literal&& other) : MutableLiteralBase() { *this = std::move(other); } Literal& Literal::operator=(Literal&& other) { DCHECK(&other.root_piece_.subshape() == other.shape_.get()); using std::swap; swap(shape_, other.shape_); swap(root_piece_, other.root_piece_); DCHECK(&root_piece_.subshape() == shape_.get()); return *this; } Literal LiteralBase::CreateFromShape(const Shape& shape) { Literal literal(shape); literal.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (piece->subshape().IsArray()) { memset(piece->untyped_data(), 0, piece->size_bytes_dense()); } }); return literal; } [&](const ShapeIndex& index, Piece* piece) { if (piece->subshape().IsArray()) { memset(piece->untyped_data(), 0, piece->size_bytes_dense()); } }); Literal LiteralBase::CreateFromShapeWithUnknownLeafArrays(const Shape& shape) { Literal literal(shape, /*allocate_arrays=*/false, ArrayValueState::kUnknown); return literal; } Literal LiteralBase::CreateFromShapeWithUndeterminedLeafArrays( const Shape& shape) { Literal literal(shape, /*allocate_arrays=*/false, ArrayValueState::kUndetermined); return literal; } int32_t LiteralBase::GetDynamicSize(int64_t dim_index) const { return GetDynamicSize(dim_index, {}); } int32_t LiteralBase::GetDynamicSize(int64_t dim_index, const ShapeIndex& shape_index) const { return piece(shape_index).GetDynamicSize(dim_index); } std::optional<int64_t> LiteralBase::GetFirstInteger() const { if (!primitive_util::IsIntegralType(shape().element_type())) { return std::nullopt; } return primitive_util::IntegralTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, void LiteralBase::BuildPieceSubtree(const Shape& shape, Piece* piece) { CHECK(shape.IsTuple()); for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); Piece child_piece; child_piece.set_subshape(&subshape); if (subshape.IsTuple()) { BuildPieceSubtree(subshape, &child_piece); } piece->emplace_back(std::move(child_piece)); } } absl::Status LiteralBase::SerializeToString(std::string* output) const { ShapeProto shape_proto = shape().ToProto(); TF_ASSIGN_OR_RETURN(int64_t size, ShapeUtil::SerializedSizeWithProto(shape(), shape_proto)); output->resize(size); return SerializeWithShapeProto(shape_proto, output->data()); } absl::StatusOr<std::string> LiteralBase::SerializeAsString() const { std::string result; TF_RETURN_IF_ERROR(SerializeToString(&result)); return std::move(result); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { void MutableLiteralBase::CopyElementFrom(const LiteralSlice& src_literal, absl::Span<const int64_t> src_index, absl::Span<const int64_t> dest_index) { DCHECK(LayoutUtil::IsDenseArray(shape())); DCHECK_EQ(shape().element_type(), src_literal.shape().element_type()); const int64_t src_linear_index = IndexUtil::MultidimensionalIndexToLinearIndex(src_literal.shape(), src_index); const int64_t dest_linear_index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), dest_index); const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); char* dest_address = static_cast<char*>(untyped_data()) + dest_linear_index * primitive_size; const char* source_address = static_cast<const char*>(src_literal.untyped_data()) + src_linear_index * primitive_size; if (dest_address != source_address) { memcpy(dest_address, source_address, primitive_size); } } /* static */ absl::StatusOr<Literal> MutableLiteralBase::CreateFromProto( const LiteralProto& proto, bool prohibit_empty_literal) { if (!proto.has_shape()) { return InvalidArgument("LiteralProto has no shape"); } Shape shape(proto.shape()); if (ShapeUtil::HasPrimitiveType(shape, OPAQUE_TYPE)) { return InvalidArgument( "Literal shape cannot include OPAQUE_TYPE sub-shape"); } if (!LayoutUtil::HasLayout(shape)) { return InvalidArgument("LiteralProto has no layout"); } if (LayoutUtil::IsSparseArray(shape)) { return Unimplemented("Sparse literals are not supported"); } TF_RETURN_IF_ERROR(ShapeUtil::ValidateShapeWithOptionalLayout(shape)); Literal literal(shape); TF_RETURN_IF_ERROR(literal.root_piece_.ForEachMutableSubpieceWithStatus( [&](const ShapeIndex& index, Piece* piece) -> absl::Status { const LiteralProto* proto_element = &proto; for (int64_t i : index) { CHECK(i < proto_element->tuple_literals_size()); proto_element = &proto_element->tuple_literals(i); } if (piece->subshape().IsTuple()) { if (proto_element->tuple_literals_size() != ShapeUtil::TupleElementCount(piece->subshape())) { return InvalidArgument( "Expected %d tuple elements in LiteralProto, has %d", ShapeUtil::TupleElementCount(piece->subshape()), proto_element->tuple_literals_size()); } return absl::OkStatus(); } if (piece->subshape().element_type() == TOKEN) { return absl::OkStatus(); } CHECK(piece->subshape().IsArray()); // When prohibit_empty_literal is false (allowing literal with no // values), only copy from proto if the literal proto has values. This // mode is used for a learned cost model. if (prohibit_empty_literal || LiteralProtoHasValues(*proto_element)) { TF_RETURN_IF_ERROR(piece->CopyFromProto(*proto_element)); } return absl::OkStatus(); })); return std::move(literal); } TF_RETURN_IF_ERROR(literal.root_piece_.ForEachMutableSubpieceWithStatus( Literal Literal::SubLiteral(ShapeIndexView shape_index) { if (!shape_index.empty()) { auto decomposed = this->DecomposeTuple(); return decomposed.at(shape_index.front()) .SubLiteral(shape_index.subspan(1)); } else { return std::move(*this); } } std::vector<Literal> Literal::DecomposeTuple() { CHECK(shape().IsTuple()); std::vector<Literal> elements; const auto tuple_element_count = ShapeUtil::TupleElementCount(shape()); elements.reserve(tuple_element_count); for (int i = 0; i < tuple_element_count; ++i) { elements.push_back(Literal(ShapeUtil::GetSubshape(shape(), {i}), /*allocate_arrays=*/false)); Literal& element = elements.back(); element.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* dest_piece) { if (dest_piece->subshape().IsTuple()) { return; } ShapeIndex src_index = {i}; for (int64_t j : index) { src_index.push_back(j); } Piece& src_piece = piece(src_index); // Move the respective buffer over to the element Literal. dest_piece->MoveDataFrom(src_piece); }); } // Set this literal to be nil-shaped. *this = Literal(); return elements; } [&](const ShapeIndex& index, Piece* dest_piece) { if (dest_piece->subshape().IsTuple()) { return; } ShapeIndex src_index = {i}; for (int64_t j : index) { src_index.push_back(j); } Piece& src_piece = piece(src_index); // Move the respective buffer over to the element Literal. dest_piece->MoveDataFrom(src_piece); }); void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } int32_t LiteralBase::Piece::GetDynamicSize(int64_t dim_index) const { CHECK(LayoutUtil::IsDenseArray(subshape())); if (!subshape_->is_dynamic_dimension(dim_index)) { // This is a static dimension, return size. return subshape_->dimensions(dim_index); } return dynamic_size_buffer()[dim_index]; } void LiteralBase::Piece::SetDynamicSize(int64_t dim_index, int32_t size) { CHECK(LayoutUtil::IsDenseArray(subshape())); CHECK(subshape_->is_dynamic_dimension(dim_index)); dynamic_size_buffer()[dim_index] = size; } void LiteralBase::Piece::AllocateBuffers() { const int64_t bytes = total_bytes_dense(); if (bytes > kMaxInlinedBytes) { CHECK_EQ(buffer(), nullptr); rep_.emplace<DenseRep>(); set_buffer( static_cast<char*>(tsl::port::AlignedMalloc(bytes, kMinimumAlignment))); } else { rep_.emplace<DenseInlinedRep>(); } } void LiteralBase::Piece::DeallocateBuffers() { if (auto* array_rep = GetDenseRep()) { tsl::port::AlignedFree(array_rep->data); rep_.emplace<Uninitialized>(); } } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } absl::Status LiteralBase::Piece::CopyFrom(const LiteralBase::Piece& src, bool only_dynamic_bound) { CHECK(subshape_ != nullptr); CHECK(src.subshape_ != nullptr); CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK(LayoutUtil::IsDenseArray(src.subshape())) << __func__ << " is only supported for dense arrays: " << src.subshape(); if (!only_dynamic_bound) { CHECK(ShapeUtil::Compatible(subshape(), src.subshape())); } if (src.array_value_state_ == ArrayValueState::kUnknown || src.array_value_state_ == ArrayValueState::kUndetermined) { if (array_value_state_ == ArrayValueState::kKnown) { DeallocateBuffers(); } array_value_state_ = src.array_value_state_; return absl::OkStatus(); } else { CHECK(src.array_value_state_ == ArrayValueState::kKnown); if (array_value_state_ == ArrayValueState::kUndetermined || array_value_state_ == ArrayValueState::kUnknown) { AllocateBuffers(); } array_value_state_ = src.array_value_state_; } if (ShapeUtil::Equal(subshape(), src.subshape())) { // If the layouts are equal it's faster just to memcpy. memcpy(buffer(), src.buffer(), src.size_bytes_dense()); } else { std::vector<int64_t> origin(subshape().rank(), 0); primitive_util::ArrayTypeSwitch<void>( [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, subshape().element_type()); } DCHECK_EQ(dynamic_size_buffer_bytes(), src.dynamic_size_buffer_bytes()); if (subshape().is_dynamic() && src.subshape().is_dynamic()) { memcpy(dynamic_size_buffer(), src.dynamic_size_buffer(), src.dynamic_size_buffer_bytes()); } return absl::OkStatus(); } [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, void MutableLiteralBase::SetDynamicSize(int64_t dim_index, int32_t size) { return SetDynamicSize(dim_index, {}, size); } void MutableLiteralBase::SetDynamicSize(int64_t dim_index, const ShapeIndex& shape_index, int32_t size) { Shape* subshape = ShapeUtil::GetMutableSubshape(mutable_shape_do_not_use(), shape_index); CHECK(LayoutUtil::IsDenseArray(*subshape)) << __func__ << " is only supported for dense arrays: " << *subshape; CHECK_GE(subshape->dimensions(dim_index), size); subshape->set_dynamic_dimension(dim_index, true); CHECK_EQ(&piece(shape_index).subshape(), subshape); piece(shape_index).SetDynamicSize(dim_index, size); } absl::Status MutableLiteralBase::CopyFrom(const LiteralSlice& src_literal, const ShapeIndex& dest_shape_index, const ShapeIndex& src_shape_index, bool only_dynamic_bound) { const Shape& dest_subshape = ShapeUtil::GetSubshape(shape(), dest_shape_index); const Shape& src_subshape = ShapeUtil::GetSubshape(src_literal.shape(), src_shape_index); if (only_dynamic_bound) { auto& bound_shape = dest_subshape.is_static() ? src_subshape : dest_subshape; auto& compact_shape = dest_subshape.is_static() ? dest_subshape : src_subshape; CHECK(ShapeUtil::DynamicShapeIsCompatible(compact_shape, bound_shape)) << compact_shape.ToString() << " vs " << bound_shape.ToString(); } else { if (!ShapeUtil::Compatible(dest_subshape, src_subshape)) { return InvalidArgument( "Destination subshape incompatible with source subshape: %s vs %s", ShapeUtil::HumanString(dest_subshape), ShapeUtil::HumanString(src_subshape)); } } return mutable_root_piece().ForEachMutableSubpieceWithStatus( [&](const ShapeIndex& index, Piece* piece) { if (!piece->subshape().IsArray()) { return absl::OkStatus(); } // Determine if this index is in the part of this literal that we want // to copy over from src_literal. bool in_subtree_to_copy = true; for (int i = 0; i < dest_shape_index.size(); ++i) { if (index[i] != dest_shape_index[i]) { in_subtree_to_copy = false; break; } } if (!in_subtree_to_copy) { return absl::OkStatus(); } // Construct the index of the corresponding piece in the source literal. ShapeIndex src_piece_index = src_shape_index; for (int64_t i = dest_shape_index.size(), end = index.size(); i < end; ++i) { src_piece_index.push_back(index[i]); } TF_RETURN_IF_ERROR( piece->CopyFrom(src_literal.piece(src_piece_index), /*only_dynamic_bound=*/only_dynamic_bound)); return absl::OkStatus(); }); } [&](const ShapeIndex& index, Piece* piece) { if (!piece->subshape().IsArray()) { return absl::OkStatus(); } // Determine if this index is in the part of this literal that we want // to copy over from src_literal. bool in_subtree_to_copy = true; for (int i = 0; i < dest_shape_index.size(); ++i) { if (index[i] != dest_shape_index[i]) { in_subtree_to_copy = false; break; } } if (!in_subtree_to_copy) { return absl::OkStatus(); } // Construct the index of the corresponding piece in the source literal. ShapeIndex src_piece_index = src_shape_index; for (int64_t i = dest_shape_index.size(), end = index.size(); i < end; ++i) { src_piece_index.push_back(index[i]); } TF_RETURN_IF_ERROR( piece->CopyFrom(src_literal.piece(src_piece_index), /*only_dynamic_bound=*/only_dynamic_bound)); return absl::OkStatus(); }); absl::Status Literal::MoveFrom(Literal&& src_literal, const ShapeIndex& dest_shape_index) { const Shape& dest_subshape = ShapeUtil::GetSubshape(shape(), dest_shape_index); if (!ShapeUtil::Equal(dest_subshape, src_literal.shape())) { return InvalidArgument( "Destination subshape not equal to source shape: %s vs %s", ShapeUtil::HumanString(dest_subshape), ShapeUtil::HumanString(src_literal.shape())); } src_literal.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& src_index, Piece* src_piece) { if (!src_piece->subshape().IsArray()) { return; } ShapeIndex dest_index = dest_shape_index; for (int64_t i : src_index) { dest_index.push_back(i); } Piece& dest_piece = piece(dest_index); dest_piece.DeallocateBuffers(); dest_piece.MoveDataFrom(*src_piece); }); src_literal.shape_ = MaybeOwningShapePtr(&NilShape()); src_literal.root_piece_ = Piece(); src_literal.root_piece_.set_subshape(src_literal.shape_.get()); return absl::OkStatus(); } [&](const ShapeIndex& src_index, Piece* src_piece) { if (!src_piece->subshape().IsArray()) { return; } ShapeIndex dest_index = dest_shape_index; for (int64_t i : src_index) { dest_index.push_back(i); } Piece& dest_piece = piece(dest_index); dest_piece.DeallocateBuffers(); dest_piece.MoveDataFrom(*src_piece); }); absl::Status MutableLiteralBase::CopySliceFrom( const LiteralSlice& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << shape(); TF_RET_CHECK(LayoutUtil::IsDenseArray(src_literal.shape())) << src_literal.shape(); TF_RET_CHECK(ShapeUtil::SameElementType(src_literal.shape(), shape())); TF_RET_CHECK(src_literal.shape().rank() == src_base.size()); TF_RET_CHECK(shape().rank() == dest_base.size()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, void MutableLiteralBase::PopulateR1(const tsl::core::Bitmap& values) { CHECK(shape().IsArray()); CHECK_EQ(shape().rank(), 1); CHECK_EQ(element_count(), values.bits()); CHECK_EQ(shape().element_type(), PRED); for (int64_t i = 0; i < static_cast<int64_t>(values.bits()); ++i) { Set({i}, values.get(i)); } } void MutableLiteralBase::PopulateInplaceInternal( absl::FunctionRef<void(void*, absl::Span<const int64_t>, int)> populator, bool parallel) { const Shape& this_shape = shape(); const int64_t rank = this_shape.rank(); DCHECK(LayoutUtil::IsDenseArray(this_shape)); char* const dest_base = static_cast<char*>(untyped_data()); if (rank > 0) { StrideConfig stride_config(this_shape, this_shape, this_shape.dimensions()); const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); const int64_t num_elements = ShapeUtil::ElementsIn(shape()); // If we are rank-1 and we are `parallel`, it is better to use a smaller // `step` than what `StrideConfig` does: stick the entire dimension in the // inner-most loop. if (parallel && this_shape.rank() == 1) { const int64_t thread_count = ShapeUtil::GetForEachIndexParallelThreadCount(); // Let's just divide up the array into small amounts per thread. stride_config.dest_stride = stride_config.minor_loop_size = num_elements > 32 ? std::max<int64_t>(num_elements / thread_count, 1) : num_elements; stride_config.step = {stride_config.minor_loop_size}; } auto init_function = [&](absl::Span<const int64_t> indexes, int thread_id) -> absl::StatusOr<bool> { const int64_t index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), indexes); DimensionVector minor_scan_indexes(rank, 0); std::copy(indexes.begin(), indexes.end(), minor_scan_indexes.begin()); char* dest_ptr = dest_base + index * primitive_size; char* const dest_end = dest_base + // This handles the case where minor_loop_size does not evenly divide // the most minor dimension. std::min(index + stride_config.minor_loop_size, num_elements) * primitive_size; while (dest_ptr < dest_end) { populator(dest_ptr, minor_scan_indexes, thread_id); ++minor_scan_indexes[stride_config.minor_dimension]; dest_ptr += primitive_size; } return true; }; if (parallel) { ShapeUtil::ForEachIndexParallel(this_shape, stride_config.base, stride_config.dimensions, stride_config.step, init_function); } else { ShapeUtil::ForEachIndex( this_shape, stride_config.base, stride_config.dimensions, stride_config.step, [&init_function]( absl::Span<const int64_t> indexes) -> absl::StatusOr<bool> { auto result_ignored = init_function(indexes, /*thread_id=*/-1); return true; }); } } else { // For scalars. populator(dest_base, {}, /*thread_id=*/-1); } } auto init_function = [&](absl::Span<const int64_t> indexes, int thread_id) -> absl::StatusOr<bool> { const int64_t index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), indexes); DimensionVector minor_scan_indexes(rank, 0); std::copy(indexes.begin(), indexes.end(), minor_scan_indexes.begin()); char* dest_ptr = dest_base + index * primitive_size; char* const dest_end = dest_base + // This handles the case where minor_loop_size does not evenly divide // the most minor dimension. std::min(index + stride_config.minor_loop_size, num_elements) * primitive_size; while (dest_ptr < dest_end) { populator(dest_ptr, minor_scan_indexes, thread_id); ++minor_scan_indexes[stride_config.minor_dimension]; dest_ptr += primitive_size; } return true; }; [&init_function]( absl::Span<const int64_t> indexes) -> absl::StatusOr<bool> { auto result_ignored = init_function(indexes, /*thread_id=*/-1); return true; }); absl::Status MutableLiteralBase::PopulateInplace( absl::FunctionRef<void(void*, absl::Span<const int64_t>)> populator) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); PopulateInplaceInternal( [&](void* dest, absl::Span<const int64_t> indexes, int /*thread_id*/) { return populator(dest, indexes); }, /*parallel=*/false); return absl::OkStatus(); } absl::Status MutableLiteralBase::PopulateInplaceParallel( absl::FunctionRef<void(void*, absl::Span<const int64_t>, int)> populator) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); PopulateInplaceInternal(populator, /*parallel=*/element_count() > 32); return absl::OkStatus(); } Literal LiteralBase::Relayout(const Layout& new_layout, const ShapeIndex& shape_index) const { // Create new shape with 'new_layout' set at the given shape index. Shape new_shape = shape(); Shape* subshape = ShapeUtil::GetMutableSubshape(&new_shape, shape_index); TF_CHECK_OK(LayoutUtil::ValidateLayoutForShape(new_layout, *subshape)); *subshape->mutable_layout() = new_layout; // LINT.IfChange // s4 literals are stored in uint8_t/int8_t, therefore element_size_in_bits // must be removed. if (subshape->layout().element_size_in_bits() == 4) { subshape->mutable_layout()->set_element_size_in_bits(0); } // LINT.ThenChange(//tensorflow/compiler/xla/types.h) Literal result(new_shape); TF_CHECK_OK(result.CopyFrom(*this)); return result; } Literal LiteralBase::Relayout(const Shape& shape_with_layout) const { CHECK(ShapeUtil::Compatible(shape_with_layout, shape())) << "Given shape_with_layout " << ShapeUtil::HumanString(shape_with_layout) << " not compatible with literal shape " << ShapeUtil::HumanString(shape()); Literal result = CreateFromShape(shape_with_layout); ShapeUtil::ForEachSubshape( result.shape(), [this, &result](const Shape& subshape, const ShapeIndex& index) { if (subshape.IsArray()) { TF_CHECK_OK(result.CopyFrom(*this, /*dest_shape_index=*/index, /*src_shape_index=*/index)); } }); return result; } [this, &result](const Shape& subshape, const ShapeIndex& index) { if (subshape.IsArray()) { TF_CHECK_OK(result.CopyFrom(*this, /*dest_shape_index=*/index, /*src_shape_index=*/index)); } }); Literal LiteralBase::ToBoundedDynamic(const Shape& bounded_shape) const { CHECK(bounded_shape.is_dynamic()); Literal result(bounded_shape); ShapeUtil::ForEachSubshape( shape(), [&](const Shape& subshape, const ShapeIndex& index) { if (!subshape.IsArray()) { return; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (bounded_shape.is_dynamic_dimension(i)) { result.SetDynamicSize(i, subshape.dimensions(i)); } } }); TF_CHECK_OK(result.CopyFrom(*this, {}, {}, /*only_dynamic_bound=*/true)); return result; } shape(), [&](const Shape& subshape, const ShapeIndex& index) { if (!subshape.IsArray()) { return; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (bounded_shape.is_dynamic_dimension(i)) { result.SetDynamicSize(i, subshape.dimensions(i)); } } }); Literal LiteralBase::ToStatic() const { // Create new shape with 'new_layout' set at the given shape index. Shape new_shape = shape(); ShapeUtil::ForEachMutableSubshape( &new_shape, [this](Shape* subshape, const ShapeIndex& index) { if (!subshape->IsArray()) { return; } for (int64_t i = 0; i < subshape->rank(); ++i) { // GetDynamicSize has a 32-bit return type and may truncate static // dimensions, so make sure to skip. if (!subshape->is_dynamic_dimension(i)) continue; subshape->set_dynamic_dimension(i, false); subshape->set_dimensions(i, GetDynamicSize(i, index)); } }); Literal result(new_shape); TF_CHECK_OK(result.CopyFrom(*this, {}, {}, /*only_dynamic_bound=*/true)); return result; } &new_shape, [this](Shape* subshape, const ShapeIndex& index) { if (!subshape->IsArray()) { return; } for (int64_t i = 0; i < subshape->rank(); ++i) { // GetDynamicSize has a 32-bit return type and may truncate static // dimensions, so make sure to skip. if (!subshape->is_dynamic_dimension(i)) continue; subshape->set_dynamic_dimension(i, false); subshape->set_dimensions(i, GetDynamicSize(i, index)); } }); absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { absl::StatusOr<Literal> LiteralBase::Broadcast( const Shape& result_shape, absl::Span<const int64_t> dimensions) const { const LiteralBase& src = *this; const Shape& src_shape = shape(); if (!src_shape.IsArray()) { return InvalidArgument("Broadcast only supports arrays."); } const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(src_shape.element_type()); switch (primitive_size) { case 0: return BroadcastHelper<0>(src, src_shape, result_shape, dimensions); case 1: return BroadcastHelper<1>(src, src_shape, result_shape, dimensions); case 2: return BroadcastHelper<2>(src, src_shape, result_shape, dimensions); case 4: return BroadcastHelper<4>(src, src_shape, result_shape, dimensions); case 8: return BroadcastHelper<8>(src, src_shape, result_shape, dimensions); case 16: return BroadcastHelper<16>(src, src_shape, result_shape, dimensions); default: LOG(FATAL) << "Unhandled primitive size " << primitive_size; return InvalidArgument("Unhandled primitive size"); break; } } absl::StatusOr<Literal> LiteralBase::Reshape( absl::Span<const int64_t> dimensions) const { if (!LayoutUtil::IsDenseArray(shape())) { return InvalidArgument("Reshape is only supported for dense arrays."); } if (shape().is_dynamic()) { // TODO(b/243182930): We should consider supporting dynamic reshape. return Unimplemented("Dynamic reshape is not implemented."); } Literal output; if (!LayoutUtil::IsMonotonicWithDim0Major(shape().layout())) { output = Relayout(LayoutUtil::GetDefaultLayoutForRank(shape().rank())); } else { output = Clone(); } // Because the layout is monotonic, we can simply reuse the same sequence of // values without changing their order. *output.mutable_shape_do_not_use() = ShapeUtil::MakeShape(shape().element_type(), dimensions); int64_t elements_before = ShapeUtil::ElementsIn(shape()); int64_t elements_after = ShapeUtil::ElementsIn(output.shape()); if (elements_before != elements_after) { return InvalidArgument( "Shapes before and after Literal::Reshape have different numbers " "of elements: %s vs %s.", ShapeUtil::HumanString(shape()), ShapeUtil::HumanString(output.shape())); } return std::move(output); } Literal LiteralBase::Transpose(absl::Span<const int64_t> permutation) const { CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); CHECK(shape().rank() == permutation.size() && IsPermutation(permutation)) << "Given permutation is not a permutation of dimension numbers"; // To transpose the array, we just permute the dimensions and layout, and // do a straight memory copy of the raw data set. // This is considerably faster than iterating over every array element using // the EachCell<>() and Set<>() APIs. Shape permuted_shape = ShapeUtil::PermuteDimensions(permutation, shape()); // Replace the layout with one affine to this shape, such that a // transpose operation can be performed by leaving the flat values // representation intact. // For example, consider the shape F32[11,8]{1,0} under a {1,0} permutation. // The shape with affine layout resulting from that operation will be // F32[8,11]{0,1}, since it leaves the original most minor (the 8 sized), the // most minor. // // Essentially, given MinMaj(Di) the position of the Di dimension within the // minor to major vector, and given T(Di) the index that the original Di // dimension has within the transposed array, a layout is affine if // MinMaj(Di) == TMinMaj(T(Di)), with TMinMaj() being the minor to major // vector of the affine layout. std::vector<int64_t> inverse_permutation = InversePermutation(permutation); CHECK(LayoutUtil::IsDenseArray(permuted_shape)); Layout* layout = permuted_shape.mutable_layout(); layout->clear_minor_to_major(); for (auto index : LayoutUtil::MinorToMajor(shape())) { layout->add_minor_to_major(inverse_permutation[index]); } Literal new_literal(permuted_shape); if (shape().is_dynamic()) { for (int64_t i = 0; i < shape().rank(); i++) { if (shape().is_dynamic_dimension(i)) { // Set the dynamic size of any dynamic dimension in the transposed // literal. new_literal.SetDynamicSize(inverse_permutation[i], GetDynamicSize(i)); } } } DCHECK_EQ(ShapeUtil::ByteSizeOf(new_literal.shape()), ShapeUtil::ByteSizeOf(shape())); std::memcpy(new_literal.untyped_data(), untyped_data(), size_bytes()); return new_literal; } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( Literal LiteralBase::Slice(absl::Span<const int64_t> start_indices, absl::Span<const int64_t> limit_indices) const { CHECK(shape().IsArray()) << "tuple is not supported for slice"; DimensionVector result_dimensions; for (int64_t dnum = 0; dnum < shape().rank(); ++dnum) { CHECK_GE(start_indices[dnum], 0); CHECK_LE(limit_indices[dnum], shape().dimensions(dnum)) << "dnum = " << dnum; int64_t dimension = limit_indices[dnum] - start_indices[dnum]; CHECK_GE(dimension, 0) << "dnum = " << dnum; result_dimensions.push_back(dimension); } auto result_shape = ShapeUtil::MakeShapeWithDenseLayout( shape().element_type(), result_dimensions, LayoutUtil::MinorToMajor(shape())); ShapeUtil::CopyDynamicDimensions(&result_shape, shape()); Literal result_literal(result_shape); primitive_util::ArrayTypeSwitch<void>( [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; return SliceInternal<NativeT>(*this, start_indices, result_literal); }, result_shape.element_type()); return result_literal; } Literal LiteralBase::Clone() const { Literal result(shape()); TF_CHECK_OK(result.CopyFrom(*this)); return result; } std::unique_ptr<Literal> LiteralBase::CloneToUnique() const { auto result = std::make_unique<Literal>(shape()); TF_CHECK_OK(result->CopyFrom(*this)); return result; } bool LiteralBase::IsDetermined(const ShapeIndex& shape_index) const { return piece(shape_index).IsDetermined(); } bool LiteralBase::IsKnown(const ShapeIndex& shape_index) const { return piece(shape_index).IsKnown(); } std::string LiteralBase::GetAsString(absl::Span<const int64_t> multi_index, const ShapeIndex& shape_index) const { const Shape& subshape = ShapeUtil::GetSubshape(shape(), shape_index); CHECK(LayoutUtil::IsDenseArray(subshape)); return primitive_util::ArrayTypeSwitch<std::string>( [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, subshape.element_type()); } [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, std::optional<int64_t> LiteralBase::GetIntegralAsS64( absl::Span<const int64_t> multi_index) const { CHECK(LayoutUtil::IsDenseArray(shape())); return primitive_util::PrimitiveTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, std::optional<double> LiteralBase::GetAsDouble( absl::Span<const int64_t> multi_index) const { const Shape& s = shape(); CHECK(LayoutUtil::IsDenseArray(s)); return primitive_util::PrimitiveTypeSwitch<std::optional<double>>( [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, s.element_type()); } [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, std::optional<double> LiteralBase::GetSumAsDouble( absl::Span<const int64_t> linear_indices) const { const Shape& s = shape(); CHECK(LayoutUtil::IsDenseArray(s)); if (!primitive_util::IsFloatingPointType(s.element_type())) { return std::nullopt; } return primitive_util::FloatingPointTypeSwitch<double>( [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, s.element_type()); } [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, std::optional<complex128> LiteralBase::GetAsComplex128( absl::Span<const int64_t> multi_index) const { return primitive_util::PrimitiveTypeSwitch<std::optional<complex128>>( [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, absl::Status MutableLiteralBase::SetIntegralAsS64( absl::Span<const int64_t> multi_index, int64_t value) { CHECK(LayoutUtil::IsDenseArray(shape())); return primitive_util::PrimitiveTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, absl::Status MutableLiteralBase::SetFromDouble( absl::Span<const int64_t> multi_index, double value) { CHECK(LayoutUtil::IsDenseArray(shape())); if (!primitive_util::IsFloatingPointType(shape().element_type())) { return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); } primitive_util::FloatingPointTypeSwitch<void>( [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, shape().element_type()); return absl::OkStatus(); } [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, void PrintShape(bool print_layout, const Shape& shape, Printer* printer) { if (print_layout) { ShapeUtil::PrintHumanStringWithLayout(printer, shape); } else { ShapeUtil::PrintHumanString(printer, shape); } } void TuplePrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); printer->Append(oneline ? "( " : "(\n"); for (int i = 0; i < ShapeUtil::TupleElementCount(subshape); ++i) { ShapeIndex element_index = shape_index; element_index.push_back(i); if (i > 0) printer->Append(oneline ? ", " : ",\n"); PrintHelper(literal, element_index, print_shape, print_layout, oneline, printer); } printer->Append(oneline ? " )" : "\n)"); } void DenseArrayPrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); int64_t rank = subshape.rank(); const absl::string_view linebreak = oneline ? " " : "\n"; std::function<void(absl::Span<const int64_t> dimensions, std::vector<int64_t>*)> print_recursive = [&](absl::Span<const int64_t> dimensions, std::vector<int64_t>* accum_indices) { // dimensions.size() decreases by 1 at each recursive call, // and accum_indices->size() increases by 1. // Their sum is equal to the rank of the tensor. CHECK_EQ(rank, dimensions.size() + accum_indices->size()); auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; if (dimensions.empty()) { // Display predicates as 0s and 1s so that the string is more dense. std::string elem; if (subshape.element_type() == PRED && rank > 0) { elem = literal.Get<bool>(*accum_indices, shape_index) ? "1" : "0"; } else { elem = literal.GetAsString(*accum_indices, shape_index); } printer->Append(elem); } else { printer->Append(brace_to_string("{")); for (int i = 0; i < dimensions[0]; ++i) { accum_indices->push_back(i); print_recursive(dimensions.subspan(1), accum_indices); accum_indices->pop_back(); if (i < dimensions[0] - 1) { printer->Append(","); printer->Append(dimensions.size() > 1 ? linebreak : " "); } } printer->Append(brace_to_string("}")); } }; if (print_shape) { PrintShape(print_layout, subshape, printer); if (subshape.is_dynamic()) { printer->Append("("); for (int64_t i = 0; i < subshape.dimensions_size(); ++i) { printer->Append(literal.GetDynamicSize(i, shape_index)); if (i < subshape.dimensions_size() - 1) { printer->Append(","); } } printer->Append(")"); } printer->Append(" "); } std::vector<int64_t> indices = {}; std::vector<int64_t> dimensions; dimensions.reserve(subshape.rank()); for (int64_t i = 0; i < subshape.rank(); ++i) { dimensions.push_back(literal.GetDynamicSize(i, shape_index)); } print_recursive(dimensions, &indices); } print_recursive = [&](absl::Span<const int64_t> dimensions, std::vector<int64_t>* accum_indices) { // dimensions.size() decreases by 1 at each recursive call, // and accum_indices->size() increases by 1. // Their sum is equal to the rank of the tensor. CHECK_EQ(rank, dimensions.size() + accum_indices->size()); auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; if (dimensions.empty()) { // Display predicates as 0s and 1s so that the string is more dense. std::string elem; if (subshape.element_type() == PRED && rank > 0) { elem = literal.Get<bool>(*accum_indices, shape_index) ? "1" : "0"; } else { elem = literal.GetAsString(*accum_indices, shape_index); } printer->Append(elem); } else { printer->Append(brace_to_string("{")); for (int i = 0; i < dimensions[0]; ++i) { accum_indices->push_back(i); print_recursive(dimensions.subspan(1), accum_indices); accum_indices->pop_back(); if (i < dimensions[0] - 1) { printer->Append(","); printer->Append(dimensions.size() > 1 ? linebreak : " "); } } printer->Append(brace_to_string("}")); } }; auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; void PrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); CHECK(LayoutUtil::HasLayout(literal.shape())); CHECK(LayoutUtil::HasLayout(subshape)); if (subshape.IsTuple()) { TuplePrintHelper(literal, shape_index, print_shape, print_layout, oneline, printer); } else if (subshape.IsToken()) { printer->Append("token"); } else { CHECK(LayoutUtil::IsDenseArray(subshape)); if (literal.IsKnown(shape_index)) { DenseArrayPrintHelper(literal, shape_index, print_shape, print_layout, oneline, printer); } else { PrintShape(print_layout, subshape, printer); printer->Append(" "); if (literal.IsDetermined(shape_index)) { printer->Append("unknown"); } else { printer->Append("undetermined"); } } } } void LiteralBase::Print(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/false, /*oneline=*/false, printer); } void LiteralBase::PrintOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/false, /*oneline=*/true, printer); } void LiteralBase::PrintWithoutShape(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/false, /*print_layout=*/false, /*oneline=*/false, printer); } void LiteralBase::PrintWithoutShapeOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/false, /*print_layout=*/false, /*oneline=*/true, printer); } void LiteralBase::PrintWithLayout(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/true, /*oneline=*/false, printer); } void LiteralBase::PrintWithLayoutOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/true, /*oneline=*/true, printer); } std::string LiteralBase::ToString() const { StringPrinter printer; Print(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringOneline() const { StringPrinter printer; PrintOneline(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithoutShape() const { StringPrinter printer; PrintWithoutShape(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithoutShapeOneline() const { StringPrinter printer; PrintWithoutShapeOneline(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithLayout() const { StringPrinter printer; PrintWithLayout(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithLayoutOneline() const { StringPrinter printer; PrintWithLayoutOneline(&printer); return std::move(printer).ToString(); } void LiteralBase::EachCellAsString( absl::FunctionRef<void(absl::Span<const int64_t> indices, const std::string& value)> per_cell) const { if (ShapeUtil::IsZeroElementArray(shape())) { return; } auto indices = IndexUtil::LinearIndexToMultidimensionalIndex( shape(), /*linear_index=*/0); do { per_cell(indices, GetAsString(indices)); } while (IndexUtil::BumpIndices(shape(), absl::MakeSpan(indices))); } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { absl::StatusOr<Literal> ConvertSwitch(const LiteralBase& literal, PrimitiveType primitive_dest_type) { TF_RET_CHECK(LayoutUtil::IsDenseArray(literal.shape())); if (literal.shape().element_type() == primitive_dest_type) { return literal.Clone(); } // Source Array type requirement is ensured by IsDenseArray before. if (!primitive_util::IsArrayType(primitive_dest_type) || !primitive_util::IsArrayType(literal.shape().element_type())) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(literal.shape().element_type()), PrimitiveType_Name(primitive_dest_type)); } // At this point, we know both src & dst are array types, while src is not // complex type, so we can allocate the result literal here to avoid // duplicating it N^2 times in the conversion implementation. Literal result( ShapeUtil::ChangeElementType(literal.shape(), primitive_dest_type)); TF_RETURN_IF_ERROR(primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { return ConvertIfDestTypeMatches<primitive_type_constant>(literal, result); }, literal.shape().element_type())); return result; } absl::StatusOr<Literal> LiteralBase::Convert( PrimitiveType primitive_dest_type) const { return ConvertSwitch(*this, primitive_dest_type); } absl::StatusOr<Literal> LiteralBase::BitcastConvert( const Shape& dest_shape) const { if (ShapeUtil::ByteSizeOf(dest_shape) != ShapeUtil::ByteSizeOf(shape())) { return InvalidArgument( "Can not bitcast-convert from shape %s to a shape of different size %s", shape().ToString(), dest_shape.ToString()); } if (dest_shape.IsTuple() || shape().IsTuple()) { return InvalidArgument( "bitcast-convert is not valid for tuple shapes %s->%s", shape().ToString(), dest_shape.ToString()); } if (shape().is_dynamic() || dest_shape.is_dynamic()) { return InvalidArgument( "bitcast-convert is not valid for dynamic shape %s->%s", shape().ToString(), dest_shape.ToString()); } Literal out(dest_shape); std::memcpy(out.root_piece_.buffer(), root_piece().buffer(), root_piece().size_bytes_dense()); // Perform the reshape on little endian encoding even on big endian machines. if constexpr (!kLittleEndian) { // Swap byte ordering as per the input data type. size_t input_elem_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); TF_RETURN_IF_ERROR(tsl::ByteSwapArray( const_cast<char*>(out.root_piece().buffer()), input_elem_size, out.root_piece().size_bytes_dense() / input_elem_size)); // Swap byte ordering as per the output data type. size_t output_elem_size = ShapeUtil::ByteSizeOfPrimitiveType(dest_shape.element_type()); TF_RETURN_IF_ERROR(tsl::ByteSwapArray( const_cast<char*>(out.root_piece().buffer()), output_elem_size, out.root_piece().size_bytes_dense() / output_elem_size)); } return out; } absl::StatusOr<Literal> LiteralBase::ConvertToShape( const Shape& dest_shape) const { if (!dest_shape.IsTuple()) { return Convert(dest_shape.element_type()); } std::vector<Literal> elements; const auto tuple_element_count = ShapeUtil::TupleElementCount(shape()); elements.reserve(tuple_element_count); for (int i = 0; i < tuple_element_count; ++i) { auto element = LiteralSlice(*this, {i}); TF_ASSIGN_OR_RETURN( auto new_element, element.ConvertToShape(ShapeUtil::GetSubshape(dest_shape, {i}))); elements.push_back(std::move(new_element)); } return MutableLiteralBase::MoveIntoTuple(absl::MakeSpan(elements)); } /* static */ Literal MutableLiteralBase::MoveIntoTuple( absl::Span<Literal> elements) { std::vector<const Shape*> element_shapes; element_shapes.reserve(elements.size()); for (const Literal& element : elements) { element_shapes.push_back(&element.shape()); } Literal literal(ShapeUtil::MakeTupleShapeWithPtrs(element_shapes), /*allocate_arrays=*/false); for (int i = 0, end = elements.size(); i < end; ++i) { TF_CHECK_OK( literal.MoveFrom(std::move(elements[i]), /*dest_shape_index=*/{i})); } return literal; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualDynamicSize( const LiteralBase::Piece& other) const { DCHECK(ShapeUtil::Compatible(subshape(), other.subshape())); if (subshape().is_static()) { return true; } for (int64_t i = 0; i < subshape().rank(); ++i) { if (GetDynamicSize(i) != other.GetDynamicSize(i)) { return false; } } return true; } bool LiteralBase::Piece::EqualElements(const LiteralBase::Piece& other) const { if (subshape().is_static() && ShapeUtil::Equal(subshape(), other.subshape()) && subshape().IsArray()) { CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(size_bytes_dense(), other.size_bytes_dense()); if (primitive_util::IsSubByteNonPredType(subshape().element_type())) { CHECK(!primitive_util::IsFloatingPointType(subshape().element_type())); auto one_array = buffer(); auto two_array = other.buffer(); const int bits_per_element = primitive_util::BitWidth(subshape().element_type()); const uint8_t mask = LsbMask<uint8_t>(bits_per_element); for (int64_t i = 0; i < size_bytes_dense(); ++i) { if ((one_array[i] & mask) != (two_array[i] & mask)) return false; } return true; } return memcmp(buffer(), other.buffer(), size_bytes_dense()) == 0; } std::vector<int64_t> multi_index; return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeSrcT = NativeTypeOf<primitive_type_constant>; return EqualElementsInternal<NativeSrcT>(other, &multi_index); }, subshape().element_type()); } bool LiteralBase::Equal(const LiteralBase& other, bool layout_sensitive) const { // Checking the structure of tuple literals. Checks for dense arrays are // performed below. if (!ShapeUtil::EqualStructure(shape(), other.shape())) { return false; } return root_piece().ForEachSubpieceWithBool([&](const ShapeIndex& index, const Piece& piece) { const Piece& other_piece = other.piece(index); const Shape& subshape = piece.subshape(); const Shape& other_subshape = other_piece.subshape(); if (subshape.element_type() != other_subshape.element_type()) { return false; } if (!piece.subshape().IsArray()) { return true; } if (subshape.rank() != other_subshape.rank()) { return false; } if (layout_sensitive && (subshape.layout() != other_subshape.layout())) { return false; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (piece.GetDynamicSize(i) != other_piece.GetDynamicSize(i)) { return false; } } if (!piece.EqualElements(other_piece)) { return false; } return true; }); } return root_piece().ForEachSubpieceWithBool([&](const ShapeIndex& index, const Piece& piece) { const Piece& other_piece = other.piece(index); const Shape& subshape = piece.subshape(); const Shape& other_subshape = other_piece.subshape(); if (subshape.element_type() != other_subshape.element_type()) { return false; } if (!piece.subshape().IsArray()) { return true; } if (subshape.rank() != other_subshape.rank()) { return false; } if (layout_sensitive && (subshape.layout() != other_subshape.layout())) { return false; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (piece.GetDynamicSize(i) != other_piece.GetDynamicSize(i)) { return false; } } if (!piece.EqualElements(other_piece)) { return false; } return true; }); static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(std::complex<T> a, std::complex<T> b) { return EqualIncludingNan(a.real(), b.real()) && EqualIncludingNan(a.imag(), b.imag()); } static bool EqualIncludingNan(std::complex<T> a, std::complex<T> b) { return EqualIncludingNan(a.real(), b.real()) && EqualIncludingNan(a.imag(), b.imag()); } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } bool Literal::Piece::IsAll(const Literal& scalar) const { CHECK(ShapeUtil::IsScalar(scalar.shape())) << scalar.shape().ToString(); if (!subshape().IsArray()) { return false; } CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(subshape().element_type(), scalar.shape().element_type()); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, subshape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, int64_t Literal::Piece::CountAll(const Literal& scalar) const { CHECK(ShapeUtil::IsScalar(scalar.shape())) << scalar.shape().ToString(); if (!subshape().IsArray()) { return 0; } CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(subshape().element_type(), scalar.shape().element_type()); return primitive_util::ArrayTypeSwitch<int64_t>( [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, subshape().element_type()); } [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { bool LiteralBase::IsAll(const Literal& scalar) const { return root_piece().IsAll(scalar); } bool LiteralBase::IsAll(int8_t value) const { if (!shape().IsArray()) { return false; } PrimitiveType ty = shape().element_type(); if (primitive_util::IsFloatingPointType(ty)) { return IsAllFloatImpl(value, /*round_value=*/false); } if (primitive_util::IsUnsignedIntegralType(ty) && value < 0) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllFloat(float value) const { return IsAllFloatImpl(value, /*round_value=*/true); } bool LiteralBase::IsAllFloatImpl(float value, bool round_value) const { PrimitiveType ty = shape().element_type(); if (!primitive_util::IsFloatingPointType(ty)) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::FloatingPointTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllComplex(complex64 value) const { PrimitiveType ty = shape().element_type(); if (!primitive_util::IsComplexType(ty)) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::ComplexTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllFirst() const { if (!shape().IsArray()) { return false; } // Empty shapes are not all the first element since there is no first element. if (ShapeUtil::IsZeroElementArray(shape())) { return false; } absl::InlinedVector<int64_t, 4> start_indices(/*n=*/shape().rank(), 0); absl::InlinedVector<int64_t, 4> end_indices(/*n=*/shape().rank(), 1); Literal first = Slice(start_indices, end_indices); return IsAll(first.Reshape({}).value()); } bool LiteralBase::IsR1Iota() const { if (!shape().IsArray()) { return false; } CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); if (shape().rank() != 1) { return false; } return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, shape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, std::optional<int64_t> LiteralBase::IsR1StridedIota() const { if (!shape().IsArray() || shape().rank() != 1) { return std::nullopt; } CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); const int64_t elements = ShapeUtil::ElementsIn(shape()); const PrimitiveType type = shape().element_type(); if (elements <= 1 || !primitive_util::IsIntegralType(type)) { return std::nullopt; } return primitive_util::IntegralTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, bool LiteralBase::IsZero(absl::Span<const int64_t> indices) const { CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, shape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void LiteralBase::Piece::set_array_value_state(ArrayValueState state) { array_value_state_ = state; } LiteralBase::ArrayValueState LiteralBase::Piece::get_array_value_state() const { return array_value_state_; } void LiteralBase::Piece::WriteToProto(LiteralProto* proto) const { *proto->mutable_shape() = subshape().ToProto(); switch (subshape().element_type()) { case PRED: CopyToRepeatedField(proto->mutable_preds(), data<bool>()); break; case U2: *proto->mutable_u2s() = std::string( reinterpret_cast<const char*>(data<u2>().data()), size_bytes_dense()); break; case U4: *proto->mutable_u4s() = std::string( reinterpret_cast<const char*>(data<u4>().data()), size_bytes_dense()); break; case U8: proto->set_u8s(static_cast<const unsigned char*>(data<uint8_t>().data()), element_count()); break; case U16: *proto->mutable_u16s() = std::string(reinterpret_cast<const char*>(data<uint16_t>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_u16s()); } break; case U32: CopyToRepeatedField(proto->mutable_u32s(), data<uint32_t>()); break; case U64: CopyToRepeatedField(proto->mutable_u64s(), data<uint64_t>()); break; case S2: *proto->mutable_s2s() = std::string( reinterpret_cast<const char*>(data<s2>().data()), size_bytes_dense()); break; case S4: *proto->mutable_s4s() = std::string( reinterpret_cast<const char*>(data<s4>().data()), size_bytes_dense()); break; case S8: proto->set_s8s(static_cast<const signed char*>(data<int8_t>().data()), element_count()); break; case S16: *proto->mutable_s16s() = std::string(reinterpret_cast<const char*>(data<int16_t>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_s16s()); } break; case S32: CopyToRepeatedField(proto->mutable_s32s(), data<int32_t>()); break; case S64: CopyToRepeatedField(proto->mutable_s64s(), data<int64_t>()); break; case F8E5M2: *proto->mutable_f8e5m2s() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e5m2>().data()), size_bytes_dense()); break; case F8E4M3FN: *proto->mutable_f8e4m3fns() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3fn>().data()), size_bytes_dense()); break; case F8E4M3B11FNUZ: *proto->mutable_f8e4m3b11fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3b11fnuz>().data()), size_bytes_dense()); break; case F8E5M2FNUZ: *proto->mutable_f8e5m2fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e5m2fnuz>().data()), size_bytes_dense()); break; case F8E4M3FNUZ: *proto->mutable_f8e4m3fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3fnuz>().data()), size_bytes_dense()); break; case F16: *proto->mutable_f16s() = std::string(reinterpret_cast<const char*>(data<half>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_f16s()); } break; case BF16: *proto->mutable_bf16s() = std::string(reinterpret_cast<const char*>(data<bfloat16>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_bf16s()); } break; case F32: CopyToRepeatedField(proto->mutable_f32s(), data<float>()); break; case F64: CopyToRepeatedField(proto->mutable_f64s(), data<double>()); break; case C64: for (complex64 value : data<complex64>()) { proto->add_c64s(value.real()); proto->add_c64s(value.imag()); } break; case C128: for (complex128 value : data<complex128>()) { proto->add_c128s(value.real()); proto->add_c128s(value.imag()); } break; case TUPLE: case TOKEN: // Nothing to do but assign the shape which is done above. return; default: // TODO(b/111551621): Support serializing more PrimitiveTypes. LOG(FATAL) << "Unhandled primitive type " << PrimitiveType_Name(subshape().element_type()); } } const void* LiteralBase::Piece::untyped_data() const { DCHECK(LayoutUtil::IsDenseArray(subshape())) << ShapeUtil::HumanString(subshape()); return buffer(); } void* LiteralBase::Piece::untyped_data() { DCHECK(LayoutUtil::IsDenseArray(subshape())) << ShapeUtil::HumanString(subshape()); return buffer(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status LiteralBase::Piece::CopyFromProto(const LiteralProto& proto) { // These conditions should have been checked in // MutableLiteralBase::CreateFromProto. TF_RET_CHECK(proto.has_shape()); Shape shape(proto.shape()); TF_RET_CHECK(LayoutUtil::HasLayout(shape)); TF_RET_CHECK(ShapeUtil::Equal(shape, subshape())); switch (subshape().element_type()) { case PRED: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<bool>(), proto.preds())); break; case S2: { const std::string& s(proto.s2s()); TF_RET_CHECK(data<s2>().size() * sizeof(s2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case S4: { const std::string& s(proto.s4s()); TF_RET_CHECK(data<s4>().size() * sizeof(s4) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case S8: { auto s8_data = data<int8_t>(); TF_RET_CHECK(proto.s8s().size() == s8_data.size()); std::copy(proto.s8s().begin(), proto.s8s().end(), s8_data.begin()); break; } case S16: { const std::string& s(proto.s16s()); TF_RET_CHECK(data<int16_t>().size() * sizeof(int16_t) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case S32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<int32_t>(), proto.s32s())); break; case S64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<int64_t>(), proto.s64s())); break; case U2: { const std::string& s(proto.u2s()); TF_RET_CHECK(data<u2>().size() * sizeof(u2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case U4: { const std::string& s(proto.u4s()); TF_RET_CHECK(data<u4>().size() * sizeof(u4) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case U8: { auto u8_data = data<uint8_t>(); TF_RET_CHECK(proto.u8s().size() == u8_data.size()); std::copy(proto.u8s().begin(), proto.u8s().end(), u8_data.begin()); break; } case U16: { const std::string& s(proto.u16s()); TF_RET_CHECK(data<uint16_t>().size() * sizeof(uint16_t) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case U32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<uint32_t>(), proto.u32s())); break; case U64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<uint64_t>(), proto.u64s())); break; case F8E5M2: { const std::string& s(proto.f8e5m2s()); TF_RET_CHECK(data<tsl::float8_e5m2>().size() * sizeof(tsl::float8_e5m2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3FN: { const std::string& s(proto.f8e4m3fns()); TF_RET_CHECK(data<tsl::float8_e4m3fn>().size() * sizeof(tsl::float8_e4m3fn) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3B11FNUZ: { const std::string& s(proto.f8e4m3b11fnuzs()); TF_RET_CHECK(data<tsl::float8_e4m3b11fnuz>().size() * sizeof(tsl::float8_e4m3b11fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E5M2FNUZ: { const std::string& s(proto.f8e5m2fnuzs()); TF_RET_CHECK(data<tsl::float8_e5m2fnuz>().size() * sizeof(tsl::float8_e5m2fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3FNUZ: { const std::string& s(proto.f8e4m3fnuzs()); TF_RET_CHECK(data<tsl::float8_e4m3fnuz>().size() * sizeof(tsl::float8_e4m3fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F16: { const std::string& s(proto.f16s()); TF_RET_CHECK(data<half>().size() * sizeof(half) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case BF16: { const std::string& s(proto.bf16s()); TF_RET_CHECK(data<bfloat16>().size() * sizeof(bfloat16) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case F32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<float>(), proto.f32s())); break; case F64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<double>(), proto.f64s())); break; case C64: { auto complex_data = data<complex64>(); TF_RET_CHECK(proto.c64s_size() == complex_data.size() * 2); for (int64_t i = 0; i < complex_data.size(); ++i) { complex_data[i] = complex64{proto.c64s(i * 2), proto.c64s(i * 2 + 1)}; } break; } case C128: { auto complex_data = data<complex128>(); const int64_t complex_data_size_doubled = complex_data.size() * 2; TF_RET_CHECK(proto.c128s_size() == complex_data_size_doubled); for (int64_t i = 0, end = complex_data.size(); i < end; ++i) { complex_data[i] = complex128{proto.c128s(i * 2), proto.c128s(i * 2 + 1)}; } break; } case TUPLE: return InvalidArgument("Should not be called on tuple shapes: %s", ShapeUtil::HumanString(subshape())); default: return InvalidArgument("Is called on unsupported shape: %s", ShapeUtil::HumanString(subshape())); } return absl::OkStatus(); } bool LiteralBase::Piece::IsKnown() const { if (array_value_state_ != ArrayValueState::kKnown) { return false; } if (subshape().IsTuple()) { bool are_all_leaf_arrays_known = true; ForEachSubpiece([&are_all_leaf_arrays_known](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_known &= piece.IsKnown(); }); return are_all_leaf_arrays_known; } return true; } ForEachSubpiece([&are_all_leaf_arrays_known](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_known &= piece.IsKnown(); }); bool LiteralBase::Piece::IsDetermined() const { if (array_value_state_ == ArrayValueState::kUndetermined) { return false; } if (subshape().IsTuple()) { bool are_all_leaf_arrays_determined = true; ForEachSubpiece([&are_all_leaf_arrays_determined](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_determined &= piece.IsDetermined(); }); return are_all_leaf_arrays_determined; } return true; } ForEachSubpiece([&are_all_leaf_arrays_determined](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_determined &= piece.IsDetermined(); }); LiteralProto LiteralBase::ToProto() const { LiteralProto proto; root_piece().ForEachSubpiece( [&](const ShapeIndex& index, const Piece& piece) { LiteralProto* proto_piece = &proto; for (int64_t i : index) { while (proto_piece->tuple_literals_size() <= i) { proto_piece->add_tuple_literals(); } proto_piece = proto_piece->mutable_tuple_literals(i); } piece.WriteToProto(proto_piece); }); return proto; } [&](const ShapeIndex& index, const Piece& piece) { LiteralProto* proto_piece = &proto; for (int64_t i : index) { while (proto_piece->tuple_literals_size() <= i) { proto_piece->add_tuple_literals(); } proto_piece = proto_piece->mutable_tuple_literals(i); } piece.WriteToProto(proto_piece); }); const void* LiteralBase::untyped_data(const ShapeIndex& shape_index) const { return piece(shape_index).untyped_data(); } void* MutableLiteralBase::untyped_data(const ShapeIndex& shape_index) { return piece(shape_index).untyped_data(); } int64_t LiteralBase::size_bytes(const ShapeIndex& shape_index) const { return piece(shape_index).size_bytes_dense(); } std::string LiteralBase::GetR1U8AsString() const { CHECK(shape().IsArray()); CHECK_EQ(shape().rank(), 1); CHECK_EQ(shape().element_type(), U8); return std::string(absl::bit_cast<const char*>(data<uint8_t>().data()), ShapeUtil::ElementsIn(shape())); } void MutableBorrowingLiteral::CopyPieceSubtree(const Shape& shape, const Piece* src_piece, Piece* dest_piece) { DCHECK(ShapeUtil::Equal(src_piece->subshape(), dest_piece->subshape())) << "src_piece has shape: " << ShapeUtil::HumanString(src_piece->subshape()) << "dest_piece has shape: " << ShapeUtil::HumanString(dest_piece->subshape()); dest_piece->set_array_value_state(src_piece->get_array_value_state()); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); Piece child_piece; child_piece.set_subshape(&subshape); CopyPieceSubtree(subshape, &src_piece->child(i), &child_piece); dest_piece->emplace_back(std::move(child_piece)); } } else if (shape.IsArray()) { dest_piece->set_buffer(const_cast<char*>(src_piece->buffer())); } } MutableLiteralBase::~MutableLiteralBase() = default; MutableBorrowingLiteral::MutableBorrowingLiteral( const MutableBorrowingLiteral& literal) : MutableLiteralBase() { shape_ = literal.shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.root_piece(), root_piece_); } MutableBorrowingLiteral& MutableBorrowingLiteral::operator=( const MutableBorrowingLiteral& literal) { shape_ = literal.shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.root_piece(), root_piece_); return *this; } MutableBorrowingLiteral::MutableBorrowingLiteral(MutableLiteralBase* literal) : MutableLiteralBase() { shape_ = literal->shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal->root_piece(), root_piece_); } MutableBorrowingLiteral::MutableBorrowingLiteral( MutableBorrowingLiteral literal, const ShapeIndex& view_root) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(literal.piece(view_root).subshape()); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.piece(view_root), root_piece_); } MutableBorrowingLiteral::MutableBorrowingLiteral(const char* src_buf_ptr, const Shape& shape) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(shape); CHECK(LayoutUtil::HasLayout(*shape_)); CHECK(!shape_->IsTuple()); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); root_piece_->set_buffer(const_cast<char*>(src_buf_ptr)); } MutableBorrowingLiteral::MutableBorrowingLiteral(absl::Span<char*> src_buf_ptrs, const Shape& shape) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(shape); if (!shape_->IsTuple()) { CHECK_EQ(src_buf_ptrs.size(), 1); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); root_piece_->set_buffer(const_cast<char*>(src_buf_ptrs[0])); } else { CHECK(!ShapeUtil::IsNestedTuple(*shape_)); CHECK_EQ(src_buf_ptrs.size(), ShapeUtil::TupleElementCount(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); for (int i = 0; i < src_buf_ptrs.size(); ++i) { Piece child_piece; const auto& src_shape = shape_->tuple_shapes(i); CHECK(src_shape.IsArray()); child_piece.set_subshape(&src_shape); child_piece.set_buffer(src_buf_ptrs[i]); root_piece_->emplace_back(std::move(child_piece)); } } } MutableBorrowingLiteral::MutableBorrowingLiteral(ShapeTree<char*> src_buf_ptrs) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(src_buf_ptrs.shape()); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); BuildPieceSubtree(*shape_, root_piece_); root_piece_->ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); } [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); MutableBorrowingLiteral::~MutableBorrowingLiteral() { if (root_piece_ != nullptr) { delete root_piece_; } } LiteralSlice::LiteralSlice(const LiteralBase& literal) : LiteralBase(), root_piece_(&literal.root_piece()) {} LiteralSlice::LiteralSlice(const LiteralBase& literal, const ShapeIndex& view_root) : LiteralBase(), root_piece_(&literal.piece(view_root)) {} BorrowingLiteral::BorrowingLiteral(const char* src_buf_ptr, const Shape& shape) : LiteralBase(), shape_(std::make_unique<Shape>(shape)) { CHECK(shape_->IsArray()); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); root_piece_.set_buffer(const_cast<char*>(src_buf_ptr)); } BorrowingLiteral::BorrowingLiteral(absl::Span<const char* const> src_buf_ptrs, const Shape& shape) : LiteralBase(), shape_(std::make_unique<Shape>(shape)) { CHECK(shape_->IsTuple()); CHECK(!ShapeUtil::IsNestedTuple(*shape_)); CHECK_EQ(src_buf_ptrs.size(), ShapeUtil::TupleElementCount(*shape_)); root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); BuildPieceSubtree(*shape_, &root_piece_); for (int i = 0, end = src_buf_ptrs.size(); i < end; ++i) { const auto& src_shape = shape_->tuple_shapes(i); CHECK(src_shape.IsArray()); root_piece_.child(i).set_buffer(const_cast<char*>(src_buf_ptrs[i])); } } BorrowingLiteral::BorrowingLiteral(ShapeTree<const char*> src_buf_ptrs) : LiteralBase(), shape_(std::make_unique<Shape>(src_buf_ptrs.shape())) { root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); BuildPieceSubtree(*shape_, &root_piece_); root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); } [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); });
#include "xla/literal.h" #include <algorithm> #include <cmath> #include <complex> #include <cstdint> #include <functional> #include <limits> #include <random> #include <string> #include <tuple> #include <utility> #include <vector> #include "absl/base/casts.h" #include "absl/hash/hash.h" #include "absl/random/random.h" #include "absl/status/status.h" #include "absl/strings/match.h" #include "absl/types/span.h" #include "xla/array.h" #include "xla/array2d.h" #include "xla/array3d.h" #include "xla/array4d.h" #include "xla/index_util.h" #include "xla/layout.h" #include "xla/layout_util.h" #include "xla/literal_util.h" #include "xla/primitive_util.h" #include "xla/shape.h" #include "xla/shape_tree.h" #include "xla/shape_util.h" #include "xla/test.h" #include "xla/types.h" #include "xla/util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/errors.h" #include "tsl/platform/logging.h" // IWYU pragma: keep #include "tsl/platform/macros.h" #include "tsl/platform/ml_dtypes.h" #include "tsl/platform/statusor.h" #include "tsl/platform/test_benchmark.h" class LiteralUtilTest : public ::testing::Test { protected: LiteralUtilTest() { Array4D<float> arr4d({ // clang-format off { // i0=0 { // i1=0 {1, 2, 3}, // i2=0 {4, 5, 6}, // i2=1 {7, 8, 9}, // i2=2 }, { // i1=1 {11, 12, 13}, {14, 15, 16}, {17, 18, 19}, }, }, { // i0=1 { // i1=0 {101, 102, 103}, {104, 105, 106}, {107, 108, 109}, }, { // i1=1 {201, 202, 203}, // i2=0 {204, 205, 206}, // i2=1 {207, 208, 209}, // i2=2 }, }, // clang-format on }); layout_r2_dim0major_ = LayoutUtil::MakeLayout({1, 0}); layout_r2_dim0minor_ = LayoutUtil::MakeLayout({0, 1}); layout_r3_dim0major_ = LayoutUtil::MakeLayout({2, 1, 0}); layout_r3_dim0minor_ = LayoutUtil::MakeLayout({0, 1, 2}); layout_r4_dim0major_ = LayoutUtil::MakeLayout({3, 2, 1, 0}); layout_r4_dim0minor_ = LayoutUtil::MakeLayout({0, 1, 2, 3}); literal_r4_2x2x3x3_dim0major_ = LiteralUtil::CreateR4FromArray4DWithLayout<float>(arr4d, layout_r4_dim0major_); literal_r4_2x2x3x3_dim0minor_ = LiteralUtil::CreateR4FromArray4DWithLayout<float>(arr4d, layout_r4_dim0minor_); } Layout layout_r2_dim0major_; Layout layout_r2_dim0minor_; Layout layout_r3_dim0major_; Layout layout_r3_dim0minor_; Layout layout_r4_dim0major_; Layout layout_r4_dim0minor_; Literal literal_r4_2x2x3x3_dim0major_; Literal literal_r4_2x2x3x3_dim0minor_; }; TEST_F(LiteralUtilTest, BroadcastVectorToMatrix0) { Literal literal = LiteralUtil::CreateR1<int64_t>({1, 2}); TF_ASSERT_OK_AND_ASSIGN( Literal broadcasted_literal, literal.Broadcast(/*result_shape=*/ShapeUtil::MakeShape(S64, {2, 2}), /*dimensions=*/{0})); EXPECT_EQ(broadcasted_literal, LiteralUtil::CreateR2<int64_t>({{1, 1}, {2, 2}})); }
LiteralUtilTest_BroadcastVectorToMatrix1
xla/literal_test.cc
bool LiteralProtoHasValues(const LiteralProto& proto) { return !proto.s2s().empty() || !proto.s4s().empty() || !proto.s8s().empty() || !proto.s16s().empty() || proto.s32s_size() || proto.s64s_size() || !proto.u2s().empty() || !proto.u4s().empty() || !proto.u8s().empty() || !proto.u16s().empty() || proto.u32s_size() || proto.u64s_size() || !proto.f8e5m2s().empty() || !proto.f8e4m3fns().empty() || !proto.f8e4m3b11fnuzs().empty() || !proto.f8e5m2fnuzs().empty() || !proto.f8e4m3fnuzs().empty() || !proto.f16s().empty() || !proto.bf16s().empty() || proto.f32s_size() || proto.f64s_size() || proto.c64s_size() || proto.c128s_size() || proto.preds_size() || proto.tuple_literals_size(); } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { const Shape& NilShape() { static const Shape* shape = new Shape(TUPLE, {}, {}, {}); return *shape; } const Shape* TryInternShape(const Shape& shape) { if (shape.IsTuple() && shape.tuple_shapes_size() == 0) { return &NilShape(); } if (shape.IsArray() && shape.dimensions_size() == 0 && shape.is_static() && shape.layout().tiles_size() == 0 && shape.layout().memory_space() == 0) { return &ScalarShape(shape.element_type()); } return nullptr; } StrideConfig::StrideConfig(const Shape& source_shape, const Shape& dest_shape, absl::Span<const int64_t> dimensions) : dimensions(dimensions), base(dimensions.size(), 0), step(dimensions.size(), 1) { if (!dimensions.empty()) { // Selects the shape with the largest minor dimension as the one upon // which to run the tight stride loop. if (dimensions[LayoutUtil::Minor(source_shape.layout(), 0)] >= dimensions[LayoutUtil::Minor(dest_shape.layout(), 0)]) { minor_dimension = LayoutUtil::Minor(source_shape.layout(), 0); dest_stride = IndexUtil::GetDimensionStride(dest_shape, minor_dimension); } else { minor_dimension = LayoutUtil::Minor(dest_shape.layout(), 0); source_stride = IndexUtil::GetDimensionStride(source_shape, minor_dimension); } minor_loop_size = dimensions[minor_dimension]; step[minor_dimension] = minor_loop_size; } } LiteralBase::~LiteralBase() = default; const Shape& LiteralBase::shape() const { return root_piece().subshape(); } const char* LiteralBase::Piece::buffer() const { // std::visit is avoided here due to its code size issues. if (auto* r = std::get_if<DenseRep>(&rep_)) { return r->data; } if (auto* r = std::get_if<DenseInlinedRep>(&rep_)) { return r->data; } DCHECK(std::holds_alternative<TupleRep>(rep_) || std::holds_alternative<Uninitialized>(rep_)); return nullptr; } const LiteralBase::Piece& LiteralBase::piece( const ShapeIndex& shape_index) const { const Piece* piece = &root_piece(); for (const auto i : shape_index) { DCHECK_GE(i, 0); DCHECK_LT(i, piece->children_size()); piece = &piece->child(i); } return *piece; } std::ostream& operator<<(std::ostream& out, const Literal& literal) { out << literal.ToString(); return out; } Shape* MutableLiteralBase::mutable_shape_do_not_use() { const Shape* const_shape = shape_.get(); if (!shape_.OwnsPtr()) { shape_ = MaybeOwningShapePtr(std::make_unique<Shape>(*shape_)); } Shape* shape = shape_.get_mutable(); if (shape != const_shape) { std::function<void(const Shape&, Piece*)> set_piece_shapes = [&set_piece_shapes](const Shape& shape, Piece* piece) { piece->set_subshape(&shape); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); set_piece_shapes(subshape, &piece->child(i)); } } }; set_piece_shapes(*shape, &mutable_root_piece()); } return shape; } [&set_piece_shapes](const Shape& shape, Piece* piece) { piece->set_subshape(&shape); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); set_piece_shapes(subshape, &piece->child(i)); } } }; Literal::Literal() : Literal(NilShape()) {} Literal::Literal(const Shape& shape) : Literal(shape, /*allocate_arrays=*/true) {} void Literal::SetShape(const Shape& shape) { Shape shape_storage; const Shape* shape_ptr = &shape; if (LayoutUtil::HasCustomElementSizeInBits(shape)) { shape_storage = shape; shape_storage.mutable_layout()->set_element_size_in_bits(0); shape_ptr = &shape_storage; } if (const Shape* intered_shape_ptr = TryInternShape(*shape_ptr)) { shape_ = intered_shape_ptr; } else { shape_ = std::make_unique<Shape>(*shape_ptr); } } void Literal::SetPiece(const Shape& shape, Piece* piece, bool allocate_arrays, ArrayValueState leaf_array_value_state) { if (shape.IsTuple()) { for (const Shape& subshape : shape.tuple_shapes()) { Piece child_piece; child_piece.set_subshape(&subshape); SetPiece(subshape, &child_piece, allocate_arrays, leaf_array_value_state); piece->emplace_back(std::move(child_piece)); } } else if (shape.IsArray()) { DCHECK(LayoutUtil::IsDenseArray(shape)) << "literal array storage is currently only supported for dense " "arrays: " << shape; piece->set_array_value_state(leaf_array_value_state); if (leaf_array_value_state == LiteralBase::ArrayValueState::kKnown && allocate_arrays) { piece->AllocateBuffers(); } } } Literal::Literal(const Shape& shape, bool allocate_arrays, ArrayValueState leaf_array_value_state) : MutableLiteralBase() { SetShape(shape); CHECK(leaf_array_value_state != ArrayValueState::kKnown || LayoutUtil::HasLayout(*shape_)); root_piece_.set_subshape(shape_.get()); CHECK(&root_piece_.subshape() == shape_.get()); SetPiece(*shape_, &root_piece_, allocate_arrays, leaf_array_value_state); } Literal::~Literal() { DeallocateBuffers(); } void Literal::DeallocateBuffers() { root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { piece->DeallocateBuffers(); }); } Literal::Literal(Literal&& other) : MutableLiteralBase() { *this = std::move(other); } Literal& Literal::operator=(Literal&& other) { DCHECK(&other.root_piece_.subshape() == other.shape_.get()); using std::swap; swap(shape_, other.shape_); swap(root_piece_, other.root_piece_); DCHECK(&root_piece_.subshape() == shape_.get()); return *this; } Literal LiteralBase::CreateFromShape(const Shape& shape) { Literal literal(shape); literal.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (piece->subshape().IsArray()) { memset(piece->untyped_data(), 0, piece->size_bytes_dense()); } }); return literal; } [&](const ShapeIndex& index, Piece* piece) { if (piece->subshape().IsArray()) { memset(piece->untyped_data(), 0, piece->size_bytes_dense()); } }); Literal LiteralBase::CreateFromShapeWithUnknownLeafArrays(const Shape& shape) { Literal literal(shape, /*allocate_arrays=*/false, ArrayValueState::kUnknown); return literal; } Literal LiteralBase::CreateFromShapeWithUndeterminedLeafArrays( const Shape& shape) { Literal literal(shape, /*allocate_arrays=*/false, ArrayValueState::kUndetermined); return literal; } int32_t LiteralBase::GetDynamicSize(int64_t dim_index) const { return GetDynamicSize(dim_index, {}); } int32_t LiteralBase::GetDynamicSize(int64_t dim_index, const ShapeIndex& shape_index) const { return piece(shape_index).GetDynamicSize(dim_index); } std::optional<int64_t> LiteralBase::GetFirstInteger() const { if (!primitive_util::IsIntegralType(shape().element_type())) { return std::nullopt; } return primitive_util::IntegralTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, void LiteralBase::BuildPieceSubtree(const Shape& shape, Piece* piece) { CHECK(shape.IsTuple()); for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); Piece child_piece; child_piece.set_subshape(&subshape); if (subshape.IsTuple()) { BuildPieceSubtree(subshape, &child_piece); } piece->emplace_back(std::move(child_piece)); } } absl::Status LiteralBase::SerializeToString(std::string* output) const { ShapeProto shape_proto = shape().ToProto(); TF_ASSIGN_OR_RETURN(int64_t size, ShapeUtil::SerializedSizeWithProto(shape(), shape_proto)); output->resize(size); return SerializeWithShapeProto(shape_proto, output->data()); } absl::StatusOr<std::string> LiteralBase::SerializeAsString() const { std::string result; TF_RETURN_IF_ERROR(SerializeToString(&result)); return std::move(result); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { void MutableLiteralBase::CopyElementFrom(const LiteralSlice& src_literal, absl::Span<const int64_t> src_index, absl::Span<const int64_t> dest_index) { DCHECK(LayoutUtil::IsDenseArray(shape())); DCHECK_EQ(shape().element_type(), src_literal.shape().element_type()); const int64_t src_linear_index = IndexUtil::MultidimensionalIndexToLinearIndex(src_literal.shape(), src_index); const int64_t dest_linear_index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), dest_index); const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); char* dest_address = static_cast<char*>(untyped_data()) + dest_linear_index * primitive_size; const char* source_address = static_cast<const char*>(src_literal.untyped_data()) + src_linear_index * primitive_size; if (dest_address != source_address) { memcpy(dest_address, source_address, primitive_size); } } /* static */ absl::StatusOr<Literal> MutableLiteralBase::CreateFromProto( const LiteralProto& proto, bool prohibit_empty_literal) { if (!proto.has_shape()) { return InvalidArgument("LiteralProto has no shape"); } Shape shape(proto.shape()); if (ShapeUtil::HasPrimitiveType(shape, OPAQUE_TYPE)) { return InvalidArgument( "Literal shape cannot include OPAQUE_TYPE sub-shape"); } if (!LayoutUtil::HasLayout(shape)) { return InvalidArgument("LiteralProto has no layout"); } if (LayoutUtil::IsSparseArray(shape)) { return Unimplemented("Sparse literals are not supported"); } TF_RETURN_IF_ERROR(ShapeUtil::ValidateShapeWithOptionalLayout(shape)); Literal literal(shape); TF_RETURN_IF_ERROR(literal.root_piece_.ForEachMutableSubpieceWithStatus( [&](const ShapeIndex& index, Piece* piece) -> absl::Status { const LiteralProto* proto_element = &proto; for (int64_t i : index) { CHECK(i < proto_element->tuple_literals_size()); proto_element = &proto_element->tuple_literals(i); } if (piece->subshape().IsTuple()) { if (proto_element->tuple_literals_size() != ShapeUtil::TupleElementCount(piece->subshape())) { return InvalidArgument( "Expected %d tuple elements in LiteralProto, has %d", ShapeUtil::TupleElementCount(piece->subshape()), proto_element->tuple_literals_size()); } return absl::OkStatus(); } if (piece->subshape().element_type() == TOKEN) { return absl::OkStatus(); } CHECK(piece->subshape().IsArray()); // When prohibit_empty_literal is false (allowing literal with no // values), only copy from proto if the literal proto has values. This // mode is used for a learned cost model. if (prohibit_empty_literal || LiteralProtoHasValues(*proto_element)) { TF_RETURN_IF_ERROR(piece->CopyFromProto(*proto_element)); } return absl::OkStatus(); })); return std::move(literal); } TF_RETURN_IF_ERROR(literal.root_piece_.ForEachMutableSubpieceWithStatus( Literal Literal::SubLiteral(ShapeIndexView shape_index) { if (!shape_index.empty()) { auto decomposed = this->DecomposeTuple(); return decomposed.at(shape_index.front()) .SubLiteral(shape_index.subspan(1)); } else { return std::move(*this); } } std::vector<Literal> Literal::DecomposeTuple() { CHECK(shape().IsTuple()); std::vector<Literal> elements; const auto tuple_element_count = ShapeUtil::TupleElementCount(shape()); elements.reserve(tuple_element_count); for (int i = 0; i < tuple_element_count; ++i) { elements.push_back(Literal(ShapeUtil::GetSubshape(shape(), {i}), /*allocate_arrays=*/false)); Literal& element = elements.back(); element.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* dest_piece) { if (dest_piece->subshape().IsTuple()) { return; } ShapeIndex src_index = {i}; for (int64_t j : index) { src_index.push_back(j); } Piece& src_piece = piece(src_index); // Move the respective buffer over to the element Literal. dest_piece->MoveDataFrom(src_piece); }); } // Set this literal to be nil-shaped. *this = Literal(); return elements; } [&](const ShapeIndex& index, Piece* dest_piece) { if (dest_piece->subshape().IsTuple()) { return; } ShapeIndex src_index = {i}; for (int64_t j : index) { src_index.push_back(j); } Piece& src_piece = piece(src_index); // Move the respective buffer over to the element Literal. dest_piece->MoveDataFrom(src_piece); }); void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } int32_t LiteralBase::Piece::GetDynamicSize(int64_t dim_index) const { CHECK(LayoutUtil::IsDenseArray(subshape())); if (!subshape_->is_dynamic_dimension(dim_index)) { // This is a static dimension, return size. return subshape_->dimensions(dim_index); } return dynamic_size_buffer()[dim_index]; } void LiteralBase::Piece::SetDynamicSize(int64_t dim_index, int32_t size) { CHECK(LayoutUtil::IsDenseArray(subshape())); CHECK(subshape_->is_dynamic_dimension(dim_index)); dynamic_size_buffer()[dim_index] = size; } void LiteralBase::Piece::AllocateBuffers() { const int64_t bytes = total_bytes_dense(); if (bytes > kMaxInlinedBytes) { CHECK_EQ(buffer(), nullptr); rep_.emplace<DenseRep>(); set_buffer( static_cast<char*>(tsl::port::AlignedMalloc(bytes, kMinimumAlignment))); } else { rep_.emplace<DenseInlinedRep>(); } } void LiteralBase::Piece::DeallocateBuffers() { if (auto* array_rep = GetDenseRep()) { tsl::port::AlignedFree(array_rep->data); rep_.emplace<Uninitialized>(); } } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } absl::Status LiteralBase::Piece::CopyFrom(const LiteralBase::Piece& src, bool only_dynamic_bound) { CHECK(subshape_ != nullptr); CHECK(src.subshape_ != nullptr); CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK(LayoutUtil::IsDenseArray(src.subshape())) << __func__ << " is only supported for dense arrays: " << src.subshape(); if (!only_dynamic_bound) { CHECK(ShapeUtil::Compatible(subshape(), src.subshape())); } if (src.array_value_state_ == ArrayValueState::kUnknown || src.array_value_state_ == ArrayValueState::kUndetermined) { if (array_value_state_ == ArrayValueState::kKnown) { DeallocateBuffers(); } array_value_state_ = src.array_value_state_; return absl::OkStatus(); } else { CHECK(src.array_value_state_ == ArrayValueState::kKnown); if (array_value_state_ == ArrayValueState::kUndetermined || array_value_state_ == ArrayValueState::kUnknown) { AllocateBuffers(); } array_value_state_ = src.array_value_state_; } if (ShapeUtil::Equal(subshape(), src.subshape())) { // If the layouts are equal it's faster just to memcpy. memcpy(buffer(), src.buffer(), src.size_bytes_dense()); } else { std::vector<int64_t> origin(subshape().rank(), 0); primitive_util::ArrayTypeSwitch<void>( [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, subshape().element_type()); } DCHECK_EQ(dynamic_size_buffer_bytes(), src.dynamic_size_buffer_bytes()); if (subshape().is_dynamic() && src.subshape().is_dynamic()) { memcpy(dynamic_size_buffer(), src.dynamic_size_buffer(), src.dynamic_size_buffer_bytes()); } return absl::OkStatus(); } [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, void MutableLiteralBase::SetDynamicSize(int64_t dim_index, int32_t size) { return SetDynamicSize(dim_index, {}, size); } void MutableLiteralBase::SetDynamicSize(int64_t dim_index, const ShapeIndex& shape_index, int32_t size) { Shape* subshape = ShapeUtil::GetMutableSubshape(mutable_shape_do_not_use(), shape_index); CHECK(LayoutUtil::IsDenseArray(*subshape)) << __func__ << " is only supported for dense arrays: " << *subshape; CHECK_GE(subshape->dimensions(dim_index), size); subshape->set_dynamic_dimension(dim_index, true); CHECK_EQ(&piece(shape_index).subshape(), subshape); piece(shape_index).SetDynamicSize(dim_index, size); } absl::Status MutableLiteralBase::CopyFrom(const LiteralSlice& src_literal, const ShapeIndex& dest_shape_index, const ShapeIndex& src_shape_index, bool only_dynamic_bound) { const Shape& dest_subshape = ShapeUtil::GetSubshape(shape(), dest_shape_index); const Shape& src_subshape = ShapeUtil::GetSubshape(src_literal.shape(), src_shape_index); if (only_dynamic_bound) { auto& bound_shape = dest_subshape.is_static() ? src_subshape : dest_subshape; auto& compact_shape = dest_subshape.is_static() ? dest_subshape : src_subshape; CHECK(ShapeUtil::DynamicShapeIsCompatible(compact_shape, bound_shape)) << compact_shape.ToString() << " vs " << bound_shape.ToString(); } else { if (!ShapeUtil::Compatible(dest_subshape, src_subshape)) { return InvalidArgument( "Destination subshape incompatible with source subshape: %s vs %s", ShapeUtil::HumanString(dest_subshape), ShapeUtil::HumanString(src_subshape)); } } return mutable_root_piece().ForEachMutableSubpieceWithStatus( [&](const ShapeIndex& index, Piece* piece) { if (!piece->subshape().IsArray()) { return absl::OkStatus(); } // Determine if this index is in the part of this literal that we want // to copy over from src_literal. bool in_subtree_to_copy = true; for (int i = 0; i < dest_shape_index.size(); ++i) { if (index[i] != dest_shape_index[i]) { in_subtree_to_copy = false; break; } } if (!in_subtree_to_copy) { return absl::OkStatus(); } // Construct the index of the corresponding piece in the source literal. ShapeIndex src_piece_index = src_shape_index; for (int64_t i = dest_shape_index.size(), end = index.size(); i < end; ++i) { src_piece_index.push_back(index[i]); } TF_RETURN_IF_ERROR( piece->CopyFrom(src_literal.piece(src_piece_index), /*only_dynamic_bound=*/only_dynamic_bound)); return absl::OkStatus(); }); } [&](const ShapeIndex& index, Piece* piece) { if (!piece->subshape().IsArray()) { return absl::OkStatus(); } // Determine if this index is in the part of this literal that we want // to copy over from src_literal. bool in_subtree_to_copy = true; for (int i = 0; i < dest_shape_index.size(); ++i) { if (index[i] != dest_shape_index[i]) { in_subtree_to_copy = false; break; } } if (!in_subtree_to_copy) { return absl::OkStatus(); } // Construct the index of the corresponding piece in the source literal. ShapeIndex src_piece_index = src_shape_index; for (int64_t i = dest_shape_index.size(), end = index.size(); i < end; ++i) { src_piece_index.push_back(index[i]); } TF_RETURN_IF_ERROR( piece->CopyFrom(src_literal.piece(src_piece_index), /*only_dynamic_bound=*/only_dynamic_bound)); return absl::OkStatus(); }); absl::Status Literal::MoveFrom(Literal&& src_literal, const ShapeIndex& dest_shape_index) { const Shape& dest_subshape = ShapeUtil::GetSubshape(shape(), dest_shape_index); if (!ShapeUtil::Equal(dest_subshape, src_literal.shape())) { return InvalidArgument( "Destination subshape not equal to source shape: %s vs %s", ShapeUtil::HumanString(dest_subshape), ShapeUtil::HumanString(src_literal.shape())); } src_literal.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& src_index, Piece* src_piece) { if (!src_piece->subshape().IsArray()) { return; } ShapeIndex dest_index = dest_shape_index; for (int64_t i : src_index) { dest_index.push_back(i); } Piece& dest_piece = piece(dest_index); dest_piece.DeallocateBuffers(); dest_piece.MoveDataFrom(*src_piece); }); src_literal.shape_ = MaybeOwningShapePtr(&NilShape()); src_literal.root_piece_ = Piece(); src_literal.root_piece_.set_subshape(src_literal.shape_.get()); return absl::OkStatus(); } [&](const ShapeIndex& src_index, Piece* src_piece) { if (!src_piece->subshape().IsArray()) { return; } ShapeIndex dest_index = dest_shape_index; for (int64_t i : src_index) { dest_index.push_back(i); } Piece& dest_piece = piece(dest_index); dest_piece.DeallocateBuffers(); dest_piece.MoveDataFrom(*src_piece); }); absl::Status MutableLiteralBase::CopySliceFrom( const LiteralSlice& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << shape(); TF_RET_CHECK(LayoutUtil::IsDenseArray(src_literal.shape())) << src_literal.shape(); TF_RET_CHECK(ShapeUtil::SameElementType(src_literal.shape(), shape())); TF_RET_CHECK(src_literal.shape().rank() == src_base.size()); TF_RET_CHECK(shape().rank() == dest_base.size()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, void MutableLiteralBase::PopulateR1(const tsl::core::Bitmap& values) { CHECK(shape().IsArray()); CHECK_EQ(shape().rank(), 1); CHECK_EQ(element_count(), values.bits()); CHECK_EQ(shape().element_type(), PRED); for (int64_t i = 0; i < static_cast<int64_t>(values.bits()); ++i) { Set({i}, values.get(i)); } } void MutableLiteralBase::PopulateInplaceInternal( absl::FunctionRef<void(void*, absl::Span<const int64_t>, int)> populator, bool parallel) { const Shape& this_shape = shape(); const int64_t rank = this_shape.rank(); DCHECK(LayoutUtil::IsDenseArray(this_shape)); char* const dest_base = static_cast<char*>(untyped_data()); if (rank > 0) { StrideConfig stride_config(this_shape, this_shape, this_shape.dimensions()); const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); const int64_t num_elements = ShapeUtil::ElementsIn(shape()); // If we are rank-1 and we are `parallel`, it is better to use a smaller // `step` than what `StrideConfig` does: stick the entire dimension in the // inner-most loop. if (parallel && this_shape.rank() == 1) { const int64_t thread_count = ShapeUtil::GetForEachIndexParallelThreadCount(); // Let's just divide up the array into small amounts per thread. stride_config.dest_stride = stride_config.minor_loop_size = num_elements > 32 ? std::max<int64_t>(num_elements / thread_count, 1) : num_elements; stride_config.step = {stride_config.minor_loop_size}; } auto init_function = [&](absl::Span<const int64_t> indexes, int thread_id) -> absl::StatusOr<bool> { const int64_t index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), indexes); DimensionVector minor_scan_indexes(rank, 0); std::copy(indexes.begin(), indexes.end(), minor_scan_indexes.begin()); char* dest_ptr = dest_base + index * primitive_size; char* const dest_end = dest_base + // This handles the case where minor_loop_size does not evenly divide // the most minor dimension. std::min(index + stride_config.minor_loop_size, num_elements) * primitive_size; while (dest_ptr < dest_end) { populator(dest_ptr, minor_scan_indexes, thread_id); ++minor_scan_indexes[stride_config.minor_dimension]; dest_ptr += primitive_size; } return true; }; if (parallel) { ShapeUtil::ForEachIndexParallel(this_shape, stride_config.base, stride_config.dimensions, stride_config.step, init_function); } else { ShapeUtil::ForEachIndex( this_shape, stride_config.base, stride_config.dimensions, stride_config.step, [&init_function]( absl::Span<const int64_t> indexes) -> absl::StatusOr<bool> { auto result_ignored = init_function(indexes, /*thread_id=*/-1); return true; }); } } else { // For scalars. populator(dest_base, {}, /*thread_id=*/-1); } } auto init_function = [&](absl::Span<const int64_t> indexes, int thread_id) -> absl::StatusOr<bool> { const int64_t index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), indexes); DimensionVector minor_scan_indexes(rank, 0); std::copy(indexes.begin(), indexes.end(), minor_scan_indexes.begin()); char* dest_ptr = dest_base + index * primitive_size; char* const dest_end = dest_base + // This handles the case where minor_loop_size does not evenly divide // the most minor dimension. std::min(index + stride_config.minor_loop_size, num_elements) * primitive_size; while (dest_ptr < dest_end) { populator(dest_ptr, minor_scan_indexes, thread_id); ++minor_scan_indexes[stride_config.minor_dimension]; dest_ptr += primitive_size; } return true; }; [&init_function]( absl::Span<const int64_t> indexes) -> absl::StatusOr<bool> { auto result_ignored = init_function(indexes, /*thread_id=*/-1); return true; }); absl::Status MutableLiteralBase::PopulateInplace( absl::FunctionRef<void(void*, absl::Span<const int64_t>)> populator) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); PopulateInplaceInternal( [&](void* dest, absl::Span<const int64_t> indexes, int /*thread_id*/) { return populator(dest, indexes); }, /*parallel=*/false); return absl::OkStatus(); } absl::Status MutableLiteralBase::PopulateInplaceParallel( absl::FunctionRef<void(void*, absl::Span<const int64_t>, int)> populator) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); PopulateInplaceInternal(populator, /*parallel=*/element_count() > 32); return absl::OkStatus(); } Literal LiteralBase::Relayout(const Layout& new_layout, const ShapeIndex& shape_index) const { // Create new shape with 'new_layout' set at the given shape index. Shape new_shape = shape(); Shape* subshape = ShapeUtil::GetMutableSubshape(&new_shape, shape_index); TF_CHECK_OK(LayoutUtil::ValidateLayoutForShape(new_layout, *subshape)); *subshape->mutable_layout() = new_layout; // LINT.IfChange // s4 literals are stored in uint8_t/int8_t, therefore element_size_in_bits // must be removed. if (subshape->layout().element_size_in_bits() == 4) { subshape->mutable_layout()->set_element_size_in_bits(0); } // LINT.ThenChange(//tensorflow/compiler/xla/types.h) Literal result(new_shape); TF_CHECK_OK(result.CopyFrom(*this)); return result; } Literal LiteralBase::Relayout(const Shape& shape_with_layout) const { CHECK(ShapeUtil::Compatible(shape_with_layout, shape())) << "Given shape_with_layout " << ShapeUtil::HumanString(shape_with_layout) << " not compatible with literal shape " << ShapeUtil::HumanString(shape()); Literal result = CreateFromShape(shape_with_layout); ShapeUtil::ForEachSubshape( result.shape(), [this, &result](const Shape& subshape, const ShapeIndex& index) { if (subshape.IsArray()) { TF_CHECK_OK(result.CopyFrom(*this, /*dest_shape_index=*/index, /*src_shape_index=*/index)); } }); return result; } [this, &result](const Shape& subshape, const ShapeIndex& index) { if (subshape.IsArray()) { TF_CHECK_OK(result.CopyFrom(*this, /*dest_shape_index=*/index, /*src_shape_index=*/index)); } }); Literal LiteralBase::ToBoundedDynamic(const Shape& bounded_shape) const { CHECK(bounded_shape.is_dynamic()); Literal result(bounded_shape); ShapeUtil::ForEachSubshape( shape(), [&](const Shape& subshape, const ShapeIndex& index) { if (!subshape.IsArray()) { return; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (bounded_shape.is_dynamic_dimension(i)) { result.SetDynamicSize(i, subshape.dimensions(i)); } } }); TF_CHECK_OK(result.CopyFrom(*this, {}, {}, /*only_dynamic_bound=*/true)); return result; } shape(), [&](const Shape& subshape, const ShapeIndex& index) { if (!subshape.IsArray()) { return; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (bounded_shape.is_dynamic_dimension(i)) { result.SetDynamicSize(i, subshape.dimensions(i)); } } }); Literal LiteralBase::ToStatic() const { // Create new shape with 'new_layout' set at the given shape index. Shape new_shape = shape(); ShapeUtil::ForEachMutableSubshape( &new_shape, [this](Shape* subshape, const ShapeIndex& index) { if (!subshape->IsArray()) { return; } for (int64_t i = 0; i < subshape->rank(); ++i) { // GetDynamicSize has a 32-bit return type and may truncate static // dimensions, so make sure to skip. if (!subshape->is_dynamic_dimension(i)) continue; subshape->set_dynamic_dimension(i, false); subshape->set_dimensions(i, GetDynamicSize(i, index)); } }); Literal result(new_shape); TF_CHECK_OK(result.CopyFrom(*this, {}, {}, /*only_dynamic_bound=*/true)); return result; } &new_shape, [this](Shape* subshape, const ShapeIndex& index) { if (!subshape->IsArray()) { return; } for (int64_t i = 0; i < subshape->rank(); ++i) { // GetDynamicSize has a 32-bit return type and may truncate static // dimensions, so make sure to skip. if (!subshape->is_dynamic_dimension(i)) continue; subshape->set_dynamic_dimension(i, false); subshape->set_dimensions(i, GetDynamicSize(i, index)); } }); absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { absl::StatusOr<Literal> LiteralBase::Broadcast( const Shape& result_shape, absl::Span<const int64_t> dimensions) const { const LiteralBase& src = *this; const Shape& src_shape = shape(); if (!src_shape.IsArray()) { return InvalidArgument("Broadcast only supports arrays."); } const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(src_shape.element_type()); switch (primitive_size) { case 0: return BroadcastHelper<0>(src, src_shape, result_shape, dimensions); case 1: return BroadcastHelper<1>(src, src_shape, result_shape, dimensions); case 2: return BroadcastHelper<2>(src, src_shape, result_shape, dimensions); case 4: return BroadcastHelper<4>(src, src_shape, result_shape, dimensions); case 8: return BroadcastHelper<8>(src, src_shape, result_shape, dimensions); case 16: return BroadcastHelper<16>(src, src_shape, result_shape, dimensions); default: LOG(FATAL) << "Unhandled primitive size " << primitive_size; return InvalidArgument("Unhandled primitive size"); break; } } absl::StatusOr<Literal> LiteralBase::Reshape( absl::Span<const int64_t> dimensions) const { if (!LayoutUtil::IsDenseArray(shape())) { return InvalidArgument("Reshape is only supported for dense arrays."); } if (shape().is_dynamic()) { // TODO(b/243182930): We should consider supporting dynamic reshape. return Unimplemented("Dynamic reshape is not implemented."); } Literal output; if (!LayoutUtil::IsMonotonicWithDim0Major(shape().layout())) { output = Relayout(LayoutUtil::GetDefaultLayoutForRank(shape().rank())); } else { output = Clone(); } // Because the layout is monotonic, we can simply reuse the same sequence of // values without changing their order. *output.mutable_shape_do_not_use() = ShapeUtil::MakeShape(shape().element_type(), dimensions); int64_t elements_before = ShapeUtil::ElementsIn(shape()); int64_t elements_after = ShapeUtil::ElementsIn(output.shape()); if (elements_before != elements_after) { return InvalidArgument( "Shapes before and after Literal::Reshape have different numbers " "of elements: %s vs %s.", ShapeUtil::HumanString(shape()), ShapeUtil::HumanString(output.shape())); } return std::move(output); } Literal LiteralBase::Transpose(absl::Span<const int64_t> permutation) const { CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); CHECK(shape().rank() == permutation.size() && IsPermutation(permutation)) << "Given permutation is not a permutation of dimension numbers"; // To transpose the array, we just permute the dimensions and layout, and // do a straight memory copy of the raw data set. // This is considerably faster than iterating over every array element using // the EachCell<>() and Set<>() APIs. Shape permuted_shape = ShapeUtil::PermuteDimensions(permutation, shape()); // Replace the layout with one affine to this shape, such that a // transpose operation can be performed by leaving the flat values // representation intact. // For example, consider the shape F32[11,8]{1,0} under a {1,0} permutation. // The shape with affine layout resulting from that operation will be // F32[8,11]{0,1}, since it leaves the original most minor (the 8 sized), the // most minor. // // Essentially, given MinMaj(Di) the position of the Di dimension within the // minor to major vector, and given T(Di) the index that the original Di // dimension has within the transposed array, a layout is affine if // MinMaj(Di) == TMinMaj(T(Di)), with TMinMaj() being the minor to major // vector of the affine layout. std::vector<int64_t> inverse_permutation = InversePermutation(permutation); CHECK(LayoutUtil::IsDenseArray(permuted_shape)); Layout* layout = permuted_shape.mutable_layout(); layout->clear_minor_to_major(); for (auto index : LayoutUtil::MinorToMajor(shape())) { layout->add_minor_to_major(inverse_permutation[index]); } Literal new_literal(permuted_shape); if (shape().is_dynamic()) { for (int64_t i = 0; i < shape().rank(); i++) { if (shape().is_dynamic_dimension(i)) { // Set the dynamic size of any dynamic dimension in the transposed // literal. new_literal.SetDynamicSize(inverse_permutation[i], GetDynamicSize(i)); } } } DCHECK_EQ(ShapeUtil::ByteSizeOf(new_literal.shape()), ShapeUtil::ByteSizeOf(shape())); std::memcpy(new_literal.untyped_data(), untyped_data(), size_bytes()); return new_literal; } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( Literal LiteralBase::Slice(absl::Span<const int64_t> start_indices, absl::Span<const int64_t> limit_indices) const { CHECK(shape().IsArray()) << "tuple is not supported for slice"; DimensionVector result_dimensions; for (int64_t dnum = 0; dnum < shape().rank(); ++dnum) { CHECK_GE(start_indices[dnum], 0); CHECK_LE(limit_indices[dnum], shape().dimensions(dnum)) << "dnum = " << dnum; int64_t dimension = limit_indices[dnum] - start_indices[dnum]; CHECK_GE(dimension, 0) << "dnum = " << dnum; result_dimensions.push_back(dimension); } auto result_shape = ShapeUtil::MakeShapeWithDenseLayout( shape().element_type(), result_dimensions, LayoutUtil::MinorToMajor(shape())); ShapeUtil::CopyDynamicDimensions(&result_shape, shape()); Literal result_literal(result_shape); primitive_util::ArrayTypeSwitch<void>( [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; return SliceInternal<NativeT>(*this, start_indices, result_literal); }, result_shape.element_type()); return result_literal; } Literal LiteralBase::Clone() const { Literal result(shape()); TF_CHECK_OK(result.CopyFrom(*this)); return result; } std::unique_ptr<Literal> LiteralBase::CloneToUnique() const { auto result = std::make_unique<Literal>(shape()); TF_CHECK_OK(result->CopyFrom(*this)); return result; } bool LiteralBase::IsDetermined(const ShapeIndex& shape_index) const { return piece(shape_index).IsDetermined(); } bool LiteralBase::IsKnown(const ShapeIndex& shape_index) const { return piece(shape_index).IsKnown(); } std::string LiteralBase::GetAsString(absl::Span<const int64_t> multi_index, const ShapeIndex& shape_index) const { const Shape& subshape = ShapeUtil::GetSubshape(shape(), shape_index); CHECK(LayoutUtil::IsDenseArray(subshape)); return primitive_util::ArrayTypeSwitch<std::string>( [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, subshape.element_type()); } [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, std::optional<int64_t> LiteralBase::GetIntegralAsS64( absl::Span<const int64_t> multi_index) const { CHECK(LayoutUtil::IsDenseArray(shape())); return primitive_util::PrimitiveTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, std::optional<double> LiteralBase::GetAsDouble( absl::Span<const int64_t> multi_index) const { const Shape& s = shape(); CHECK(LayoutUtil::IsDenseArray(s)); return primitive_util::PrimitiveTypeSwitch<std::optional<double>>( [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, s.element_type()); } [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, std::optional<double> LiteralBase::GetSumAsDouble( absl::Span<const int64_t> linear_indices) const { const Shape& s = shape(); CHECK(LayoutUtil::IsDenseArray(s)); if (!primitive_util::IsFloatingPointType(s.element_type())) { return std::nullopt; } return primitive_util::FloatingPointTypeSwitch<double>( [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, s.element_type()); } [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, std::optional<complex128> LiteralBase::GetAsComplex128( absl::Span<const int64_t> multi_index) const { return primitive_util::PrimitiveTypeSwitch<std::optional<complex128>>( [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, absl::Status MutableLiteralBase::SetIntegralAsS64( absl::Span<const int64_t> multi_index, int64_t value) { CHECK(LayoutUtil::IsDenseArray(shape())); return primitive_util::PrimitiveTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, absl::Status MutableLiteralBase::SetFromDouble( absl::Span<const int64_t> multi_index, double value) { CHECK(LayoutUtil::IsDenseArray(shape())); if (!primitive_util::IsFloatingPointType(shape().element_type())) { return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); } primitive_util::FloatingPointTypeSwitch<void>( [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, shape().element_type()); return absl::OkStatus(); } [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, void PrintShape(bool print_layout, const Shape& shape, Printer* printer) { if (print_layout) { ShapeUtil::PrintHumanStringWithLayout(printer, shape); } else { ShapeUtil::PrintHumanString(printer, shape); } } void TuplePrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); printer->Append(oneline ? "( " : "(\n"); for (int i = 0; i < ShapeUtil::TupleElementCount(subshape); ++i) { ShapeIndex element_index = shape_index; element_index.push_back(i); if (i > 0) printer->Append(oneline ? ", " : ",\n"); PrintHelper(literal, element_index, print_shape, print_layout, oneline, printer); } printer->Append(oneline ? " )" : "\n)"); } void DenseArrayPrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); int64_t rank = subshape.rank(); const absl::string_view linebreak = oneline ? " " : "\n"; std::function<void(absl::Span<const int64_t> dimensions, std::vector<int64_t>*)> print_recursive = [&](absl::Span<const int64_t> dimensions, std::vector<int64_t>* accum_indices) { // dimensions.size() decreases by 1 at each recursive call, // and accum_indices->size() increases by 1. // Their sum is equal to the rank of the tensor. CHECK_EQ(rank, dimensions.size() + accum_indices->size()); auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; if (dimensions.empty()) { // Display predicates as 0s and 1s so that the string is more dense. std::string elem; if (subshape.element_type() == PRED && rank > 0) { elem = literal.Get<bool>(*accum_indices, shape_index) ? "1" : "0"; } else { elem = literal.GetAsString(*accum_indices, shape_index); } printer->Append(elem); } else { printer->Append(brace_to_string("{")); for (int i = 0; i < dimensions[0]; ++i) { accum_indices->push_back(i); print_recursive(dimensions.subspan(1), accum_indices); accum_indices->pop_back(); if (i < dimensions[0] - 1) { printer->Append(","); printer->Append(dimensions.size() > 1 ? linebreak : " "); } } printer->Append(brace_to_string("}")); } }; if (print_shape) { PrintShape(print_layout, subshape, printer); if (subshape.is_dynamic()) { printer->Append("("); for (int64_t i = 0; i < subshape.dimensions_size(); ++i) { printer->Append(literal.GetDynamicSize(i, shape_index)); if (i < subshape.dimensions_size() - 1) { printer->Append(","); } } printer->Append(")"); } printer->Append(" "); } std::vector<int64_t> indices = {}; std::vector<int64_t> dimensions; dimensions.reserve(subshape.rank()); for (int64_t i = 0; i < subshape.rank(); ++i) { dimensions.push_back(literal.GetDynamicSize(i, shape_index)); } print_recursive(dimensions, &indices); } print_recursive = [&](absl::Span<const int64_t> dimensions, std::vector<int64_t>* accum_indices) { // dimensions.size() decreases by 1 at each recursive call, // and accum_indices->size() increases by 1. // Their sum is equal to the rank of the tensor. CHECK_EQ(rank, dimensions.size() + accum_indices->size()); auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; if (dimensions.empty()) { // Display predicates as 0s and 1s so that the string is more dense. std::string elem; if (subshape.element_type() == PRED && rank > 0) { elem = literal.Get<bool>(*accum_indices, shape_index) ? "1" : "0"; } else { elem = literal.GetAsString(*accum_indices, shape_index); } printer->Append(elem); } else { printer->Append(brace_to_string("{")); for (int i = 0; i < dimensions[0]; ++i) { accum_indices->push_back(i); print_recursive(dimensions.subspan(1), accum_indices); accum_indices->pop_back(); if (i < dimensions[0] - 1) { printer->Append(","); printer->Append(dimensions.size() > 1 ? linebreak : " "); } } printer->Append(brace_to_string("}")); } }; auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; void PrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); CHECK(LayoutUtil::HasLayout(literal.shape())); CHECK(LayoutUtil::HasLayout(subshape)); if (subshape.IsTuple()) { TuplePrintHelper(literal, shape_index, print_shape, print_layout, oneline, printer); } else if (subshape.IsToken()) { printer->Append("token"); } else { CHECK(LayoutUtil::IsDenseArray(subshape)); if (literal.IsKnown(shape_index)) { DenseArrayPrintHelper(literal, shape_index, print_shape, print_layout, oneline, printer); } else { PrintShape(print_layout, subshape, printer); printer->Append(" "); if (literal.IsDetermined(shape_index)) { printer->Append("unknown"); } else { printer->Append("undetermined"); } } } } void LiteralBase::Print(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/false, /*oneline=*/false, printer); } void LiteralBase::PrintOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/false, /*oneline=*/true, printer); } void LiteralBase::PrintWithoutShape(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/false, /*print_layout=*/false, /*oneline=*/false, printer); } void LiteralBase::PrintWithoutShapeOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/false, /*print_layout=*/false, /*oneline=*/true, printer); } void LiteralBase::PrintWithLayout(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/true, /*oneline=*/false, printer); } void LiteralBase::PrintWithLayoutOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/true, /*oneline=*/true, printer); } std::string LiteralBase::ToString() const { StringPrinter printer; Print(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringOneline() const { StringPrinter printer; PrintOneline(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithoutShape() const { StringPrinter printer; PrintWithoutShape(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithoutShapeOneline() const { StringPrinter printer; PrintWithoutShapeOneline(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithLayout() const { StringPrinter printer; PrintWithLayout(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithLayoutOneline() const { StringPrinter printer; PrintWithLayoutOneline(&printer); return std::move(printer).ToString(); } void LiteralBase::EachCellAsString( absl::FunctionRef<void(absl::Span<const int64_t> indices, const std::string& value)> per_cell) const { if (ShapeUtil::IsZeroElementArray(shape())) { return; } auto indices = IndexUtil::LinearIndexToMultidimensionalIndex( shape(), /*linear_index=*/0); do { per_cell(indices, GetAsString(indices)); } while (IndexUtil::BumpIndices(shape(), absl::MakeSpan(indices))); } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { absl::StatusOr<Literal> ConvertSwitch(const LiteralBase& literal, PrimitiveType primitive_dest_type) { TF_RET_CHECK(LayoutUtil::IsDenseArray(literal.shape())); if (literal.shape().element_type() == primitive_dest_type) { return literal.Clone(); } // Source Array type requirement is ensured by IsDenseArray before. if (!primitive_util::IsArrayType(primitive_dest_type) || !primitive_util::IsArrayType(literal.shape().element_type())) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(literal.shape().element_type()), PrimitiveType_Name(primitive_dest_type)); } // At this point, we know both src & dst are array types, while src is not // complex type, so we can allocate the result literal here to avoid // duplicating it N^2 times in the conversion implementation. Literal result( ShapeUtil::ChangeElementType(literal.shape(), primitive_dest_type)); TF_RETURN_IF_ERROR(primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { return ConvertIfDestTypeMatches<primitive_type_constant>(literal, result); }, literal.shape().element_type())); return result; } absl::StatusOr<Literal> LiteralBase::Convert( PrimitiveType primitive_dest_type) const { return ConvertSwitch(*this, primitive_dest_type); } absl::StatusOr<Literal> LiteralBase::BitcastConvert( const Shape& dest_shape) const { if (ShapeUtil::ByteSizeOf(dest_shape) != ShapeUtil::ByteSizeOf(shape())) { return InvalidArgument( "Can not bitcast-convert from shape %s to a shape of different size %s", shape().ToString(), dest_shape.ToString()); } if (dest_shape.IsTuple() || shape().IsTuple()) { return InvalidArgument( "bitcast-convert is not valid for tuple shapes %s->%s", shape().ToString(), dest_shape.ToString()); } if (shape().is_dynamic() || dest_shape.is_dynamic()) { return InvalidArgument( "bitcast-convert is not valid for dynamic shape %s->%s", shape().ToString(), dest_shape.ToString()); } Literal out(dest_shape); std::memcpy(out.root_piece_.buffer(), root_piece().buffer(), root_piece().size_bytes_dense()); // Perform the reshape on little endian encoding even on big endian machines. if constexpr (!kLittleEndian) { // Swap byte ordering as per the input data type. size_t input_elem_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); TF_RETURN_IF_ERROR(tsl::ByteSwapArray( const_cast<char*>(out.root_piece().buffer()), input_elem_size, out.root_piece().size_bytes_dense() / input_elem_size)); // Swap byte ordering as per the output data type. size_t output_elem_size = ShapeUtil::ByteSizeOfPrimitiveType(dest_shape.element_type()); TF_RETURN_IF_ERROR(tsl::ByteSwapArray( const_cast<char*>(out.root_piece().buffer()), output_elem_size, out.root_piece().size_bytes_dense() / output_elem_size)); } return out; } absl::StatusOr<Literal> LiteralBase::ConvertToShape( const Shape& dest_shape) const { if (!dest_shape.IsTuple()) { return Convert(dest_shape.element_type()); } std::vector<Literal> elements; const auto tuple_element_count = ShapeUtil::TupleElementCount(shape()); elements.reserve(tuple_element_count); for (int i = 0; i < tuple_element_count; ++i) { auto element = LiteralSlice(*this, {i}); TF_ASSIGN_OR_RETURN( auto new_element, element.ConvertToShape(ShapeUtil::GetSubshape(dest_shape, {i}))); elements.push_back(std::move(new_element)); } return MutableLiteralBase::MoveIntoTuple(absl::MakeSpan(elements)); } /* static */ Literal MutableLiteralBase::MoveIntoTuple( absl::Span<Literal> elements) { std::vector<const Shape*> element_shapes; element_shapes.reserve(elements.size()); for (const Literal& element : elements) { element_shapes.push_back(&element.shape()); } Literal literal(ShapeUtil::MakeTupleShapeWithPtrs(element_shapes), /*allocate_arrays=*/false); for (int i = 0, end = elements.size(); i < end; ++i) { TF_CHECK_OK( literal.MoveFrom(std::move(elements[i]), /*dest_shape_index=*/{i})); } return literal; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualDynamicSize( const LiteralBase::Piece& other) const { DCHECK(ShapeUtil::Compatible(subshape(), other.subshape())); if (subshape().is_static()) { return true; } for (int64_t i = 0; i < subshape().rank(); ++i) { if (GetDynamicSize(i) != other.GetDynamicSize(i)) { return false; } } return true; } bool LiteralBase::Piece::EqualElements(const LiteralBase::Piece& other) const { if (subshape().is_static() && ShapeUtil::Equal(subshape(), other.subshape()) && subshape().IsArray()) { CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(size_bytes_dense(), other.size_bytes_dense()); if (primitive_util::IsSubByteNonPredType(subshape().element_type())) { CHECK(!primitive_util::IsFloatingPointType(subshape().element_type())); auto one_array = buffer(); auto two_array = other.buffer(); const int bits_per_element = primitive_util::BitWidth(subshape().element_type()); const uint8_t mask = LsbMask<uint8_t>(bits_per_element); for (int64_t i = 0; i < size_bytes_dense(); ++i) { if ((one_array[i] & mask) != (two_array[i] & mask)) return false; } return true; } return memcmp(buffer(), other.buffer(), size_bytes_dense()) == 0; } std::vector<int64_t> multi_index; return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeSrcT = NativeTypeOf<primitive_type_constant>; return EqualElementsInternal<NativeSrcT>(other, &multi_index); }, subshape().element_type()); } bool LiteralBase::Equal(const LiteralBase& other, bool layout_sensitive) const { // Checking the structure of tuple literals. Checks for dense arrays are // performed below. if (!ShapeUtil::EqualStructure(shape(), other.shape())) { return false; } return root_piece().ForEachSubpieceWithBool([&](const ShapeIndex& index, const Piece& piece) { const Piece& other_piece = other.piece(index); const Shape& subshape = piece.subshape(); const Shape& other_subshape = other_piece.subshape(); if (subshape.element_type() != other_subshape.element_type()) { return false; } if (!piece.subshape().IsArray()) { return true; } if (subshape.rank() != other_subshape.rank()) { return false; } if (layout_sensitive && (subshape.layout() != other_subshape.layout())) { return false; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (piece.GetDynamicSize(i) != other_piece.GetDynamicSize(i)) { return false; } } if (!piece.EqualElements(other_piece)) { return false; } return true; }); } return root_piece().ForEachSubpieceWithBool([&](const ShapeIndex& index, const Piece& piece) { const Piece& other_piece = other.piece(index); const Shape& subshape = piece.subshape(); const Shape& other_subshape = other_piece.subshape(); if (subshape.element_type() != other_subshape.element_type()) { return false; } if (!piece.subshape().IsArray()) { return true; } if (subshape.rank() != other_subshape.rank()) { return false; } if (layout_sensitive && (subshape.layout() != other_subshape.layout())) { return false; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (piece.GetDynamicSize(i) != other_piece.GetDynamicSize(i)) { return false; } } if (!piece.EqualElements(other_piece)) { return false; } return true; }); static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(std::complex<T> a, std::complex<T> b) { return EqualIncludingNan(a.real(), b.real()) && EqualIncludingNan(a.imag(), b.imag()); } static bool EqualIncludingNan(std::complex<T> a, std::complex<T> b) { return EqualIncludingNan(a.real(), b.real()) && EqualIncludingNan(a.imag(), b.imag()); } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } bool Literal::Piece::IsAll(const Literal& scalar) const { CHECK(ShapeUtil::IsScalar(scalar.shape())) << scalar.shape().ToString(); if (!subshape().IsArray()) { return false; } CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(subshape().element_type(), scalar.shape().element_type()); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, subshape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, int64_t Literal::Piece::CountAll(const Literal& scalar) const { CHECK(ShapeUtil::IsScalar(scalar.shape())) << scalar.shape().ToString(); if (!subshape().IsArray()) { return 0; } CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(subshape().element_type(), scalar.shape().element_type()); return primitive_util::ArrayTypeSwitch<int64_t>( [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, subshape().element_type()); } [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { bool LiteralBase::IsAll(const Literal& scalar) const { return root_piece().IsAll(scalar); } bool LiteralBase::IsAll(int8_t value) const { if (!shape().IsArray()) { return false; } PrimitiveType ty = shape().element_type(); if (primitive_util::IsFloatingPointType(ty)) { return IsAllFloatImpl(value, /*round_value=*/false); } if (primitive_util::IsUnsignedIntegralType(ty) && value < 0) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllFloat(float value) const { return IsAllFloatImpl(value, /*round_value=*/true); } bool LiteralBase::IsAllFloatImpl(float value, bool round_value) const { PrimitiveType ty = shape().element_type(); if (!primitive_util::IsFloatingPointType(ty)) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::FloatingPointTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllComplex(complex64 value) const { PrimitiveType ty = shape().element_type(); if (!primitive_util::IsComplexType(ty)) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::ComplexTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllFirst() const { if (!shape().IsArray()) { return false; } // Empty shapes are not all the first element since there is no first element. if (ShapeUtil::IsZeroElementArray(shape())) { return false; } absl::InlinedVector<int64_t, 4> start_indices(/*n=*/shape().rank(), 0); absl::InlinedVector<int64_t, 4> end_indices(/*n=*/shape().rank(), 1); Literal first = Slice(start_indices, end_indices); return IsAll(first.Reshape({}).value()); } bool LiteralBase::IsR1Iota() const { if (!shape().IsArray()) { return false; } CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); if (shape().rank() != 1) { return false; } return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, shape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, std::optional<int64_t> LiteralBase::IsR1StridedIota() const { if (!shape().IsArray() || shape().rank() != 1) { return std::nullopt; } CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); const int64_t elements = ShapeUtil::ElementsIn(shape()); const PrimitiveType type = shape().element_type(); if (elements <= 1 || !primitive_util::IsIntegralType(type)) { return std::nullopt; } return primitive_util::IntegralTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, bool LiteralBase::IsZero(absl::Span<const int64_t> indices) const { CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, shape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void LiteralBase::Piece::set_array_value_state(ArrayValueState state) { array_value_state_ = state; } LiteralBase::ArrayValueState LiteralBase::Piece::get_array_value_state() const { return array_value_state_; } void LiteralBase::Piece::WriteToProto(LiteralProto* proto) const { *proto->mutable_shape() = subshape().ToProto(); switch (subshape().element_type()) { case PRED: CopyToRepeatedField(proto->mutable_preds(), data<bool>()); break; case U2: *proto->mutable_u2s() = std::string( reinterpret_cast<const char*>(data<u2>().data()), size_bytes_dense()); break; case U4: *proto->mutable_u4s() = std::string( reinterpret_cast<const char*>(data<u4>().data()), size_bytes_dense()); break; case U8: proto->set_u8s(static_cast<const unsigned char*>(data<uint8_t>().data()), element_count()); break; case U16: *proto->mutable_u16s() = std::string(reinterpret_cast<const char*>(data<uint16_t>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_u16s()); } break; case U32: CopyToRepeatedField(proto->mutable_u32s(), data<uint32_t>()); break; case U64: CopyToRepeatedField(proto->mutable_u64s(), data<uint64_t>()); break; case S2: *proto->mutable_s2s() = std::string( reinterpret_cast<const char*>(data<s2>().data()), size_bytes_dense()); break; case S4: *proto->mutable_s4s() = std::string( reinterpret_cast<const char*>(data<s4>().data()), size_bytes_dense()); break; case S8: proto->set_s8s(static_cast<const signed char*>(data<int8_t>().data()), element_count()); break; case S16: *proto->mutable_s16s() = std::string(reinterpret_cast<const char*>(data<int16_t>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_s16s()); } break; case S32: CopyToRepeatedField(proto->mutable_s32s(), data<int32_t>()); break; case S64: CopyToRepeatedField(proto->mutable_s64s(), data<int64_t>()); break; case F8E5M2: *proto->mutable_f8e5m2s() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e5m2>().data()), size_bytes_dense()); break; case F8E4M3FN: *proto->mutable_f8e4m3fns() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3fn>().data()), size_bytes_dense()); break; case F8E4M3B11FNUZ: *proto->mutable_f8e4m3b11fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3b11fnuz>().data()), size_bytes_dense()); break; case F8E5M2FNUZ: *proto->mutable_f8e5m2fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e5m2fnuz>().data()), size_bytes_dense()); break; case F8E4M3FNUZ: *proto->mutable_f8e4m3fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3fnuz>().data()), size_bytes_dense()); break; case F16: *proto->mutable_f16s() = std::string(reinterpret_cast<const char*>(data<half>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_f16s()); } break; case BF16: *proto->mutable_bf16s() = std::string(reinterpret_cast<const char*>(data<bfloat16>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_bf16s()); } break; case F32: CopyToRepeatedField(proto->mutable_f32s(), data<float>()); break; case F64: CopyToRepeatedField(proto->mutable_f64s(), data<double>()); break; case C64: for (complex64 value : data<complex64>()) { proto->add_c64s(value.real()); proto->add_c64s(value.imag()); } break; case C128: for (complex128 value : data<complex128>()) { proto->add_c128s(value.real()); proto->add_c128s(value.imag()); } break; case TUPLE: case TOKEN: // Nothing to do but assign the shape which is done above. return; default: // TODO(b/111551621): Support serializing more PrimitiveTypes. LOG(FATAL) << "Unhandled primitive type " << PrimitiveType_Name(subshape().element_type()); } } const void* LiteralBase::Piece::untyped_data() const { DCHECK(LayoutUtil::IsDenseArray(subshape())) << ShapeUtil::HumanString(subshape()); return buffer(); } void* LiteralBase::Piece::untyped_data() { DCHECK(LayoutUtil::IsDenseArray(subshape())) << ShapeUtil::HumanString(subshape()); return buffer(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status LiteralBase::Piece::CopyFromProto(const LiteralProto& proto) { // These conditions should have been checked in // MutableLiteralBase::CreateFromProto. TF_RET_CHECK(proto.has_shape()); Shape shape(proto.shape()); TF_RET_CHECK(LayoutUtil::HasLayout(shape)); TF_RET_CHECK(ShapeUtil::Equal(shape, subshape())); switch (subshape().element_type()) { case PRED: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<bool>(), proto.preds())); break; case S2: { const std::string& s(proto.s2s()); TF_RET_CHECK(data<s2>().size() * sizeof(s2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case S4: { const std::string& s(proto.s4s()); TF_RET_CHECK(data<s4>().size() * sizeof(s4) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case S8: { auto s8_data = data<int8_t>(); TF_RET_CHECK(proto.s8s().size() == s8_data.size()); std::copy(proto.s8s().begin(), proto.s8s().end(), s8_data.begin()); break; } case S16: { const std::string& s(proto.s16s()); TF_RET_CHECK(data<int16_t>().size() * sizeof(int16_t) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case S32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<int32_t>(), proto.s32s())); break; case S64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<int64_t>(), proto.s64s())); break; case U2: { const std::string& s(proto.u2s()); TF_RET_CHECK(data<u2>().size() * sizeof(u2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case U4: { const std::string& s(proto.u4s()); TF_RET_CHECK(data<u4>().size() * sizeof(u4) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case U8: { auto u8_data = data<uint8_t>(); TF_RET_CHECK(proto.u8s().size() == u8_data.size()); std::copy(proto.u8s().begin(), proto.u8s().end(), u8_data.begin()); break; } case U16: { const std::string& s(proto.u16s()); TF_RET_CHECK(data<uint16_t>().size() * sizeof(uint16_t) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case U32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<uint32_t>(), proto.u32s())); break; case U64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<uint64_t>(), proto.u64s())); break; case F8E5M2: { const std::string& s(proto.f8e5m2s()); TF_RET_CHECK(data<tsl::float8_e5m2>().size() * sizeof(tsl::float8_e5m2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3FN: { const std::string& s(proto.f8e4m3fns()); TF_RET_CHECK(data<tsl::float8_e4m3fn>().size() * sizeof(tsl::float8_e4m3fn) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3B11FNUZ: { const std::string& s(proto.f8e4m3b11fnuzs()); TF_RET_CHECK(data<tsl::float8_e4m3b11fnuz>().size() * sizeof(tsl::float8_e4m3b11fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E5M2FNUZ: { const std::string& s(proto.f8e5m2fnuzs()); TF_RET_CHECK(data<tsl::float8_e5m2fnuz>().size() * sizeof(tsl::float8_e5m2fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3FNUZ: { const std::string& s(proto.f8e4m3fnuzs()); TF_RET_CHECK(data<tsl::float8_e4m3fnuz>().size() * sizeof(tsl::float8_e4m3fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F16: { const std::string& s(proto.f16s()); TF_RET_CHECK(data<half>().size() * sizeof(half) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case BF16: { const std::string& s(proto.bf16s()); TF_RET_CHECK(data<bfloat16>().size() * sizeof(bfloat16) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case F32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<float>(), proto.f32s())); break; case F64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<double>(), proto.f64s())); break; case C64: { auto complex_data = data<complex64>(); TF_RET_CHECK(proto.c64s_size() == complex_data.size() * 2); for (int64_t i = 0; i < complex_data.size(); ++i) { complex_data[i] = complex64{proto.c64s(i * 2), proto.c64s(i * 2 + 1)}; } break; } case C128: { auto complex_data = data<complex128>(); const int64_t complex_data_size_doubled = complex_data.size() * 2; TF_RET_CHECK(proto.c128s_size() == complex_data_size_doubled); for (int64_t i = 0, end = complex_data.size(); i < end; ++i) { complex_data[i] = complex128{proto.c128s(i * 2), proto.c128s(i * 2 + 1)}; } break; } case TUPLE: return InvalidArgument("Should not be called on tuple shapes: %s", ShapeUtil::HumanString(subshape())); default: return InvalidArgument("Is called on unsupported shape: %s", ShapeUtil::HumanString(subshape())); } return absl::OkStatus(); } bool LiteralBase::Piece::IsKnown() const { if (array_value_state_ != ArrayValueState::kKnown) { return false; } if (subshape().IsTuple()) { bool are_all_leaf_arrays_known = true; ForEachSubpiece([&are_all_leaf_arrays_known](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_known &= piece.IsKnown(); }); return are_all_leaf_arrays_known; } return true; } ForEachSubpiece([&are_all_leaf_arrays_known](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_known &= piece.IsKnown(); }); bool LiteralBase::Piece::IsDetermined() const { if (array_value_state_ == ArrayValueState::kUndetermined) { return false; } if (subshape().IsTuple()) { bool are_all_leaf_arrays_determined = true; ForEachSubpiece([&are_all_leaf_arrays_determined](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_determined &= piece.IsDetermined(); }); return are_all_leaf_arrays_determined; } return true; } ForEachSubpiece([&are_all_leaf_arrays_determined](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_determined &= piece.IsDetermined(); }); LiteralProto LiteralBase::ToProto() const { LiteralProto proto; root_piece().ForEachSubpiece( [&](const ShapeIndex& index, const Piece& piece) { LiteralProto* proto_piece = &proto; for (int64_t i : index) { while (proto_piece->tuple_literals_size() <= i) { proto_piece->add_tuple_literals(); } proto_piece = proto_piece->mutable_tuple_literals(i); } piece.WriteToProto(proto_piece); }); return proto; } [&](const ShapeIndex& index, const Piece& piece) { LiteralProto* proto_piece = &proto; for (int64_t i : index) { while (proto_piece->tuple_literals_size() <= i) { proto_piece->add_tuple_literals(); } proto_piece = proto_piece->mutable_tuple_literals(i); } piece.WriteToProto(proto_piece); }); const void* LiteralBase::untyped_data(const ShapeIndex& shape_index) const { return piece(shape_index).untyped_data(); } void* MutableLiteralBase::untyped_data(const ShapeIndex& shape_index) { return piece(shape_index).untyped_data(); } int64_t LiteralBase::size_bytes(const ShapeIndex& shape_index) const { return piece(shape_index).size_bytes_dense(); } std::string LiteralBase::GetR1U8AsString() const { CHECK(shape().IsArray()); CHECK_EQ(shape().rank(), 1); CHECK_EQ(shape().element_type(), U8); return std::string(absl::bit_cast<const char*>(data<uint8_t>().data()), ShapeUtil::ElementsIn(shape())); } void MutableBorrowingLiteral::CopyPieceSubtree(const Shape& shape, const Piece* src_piece, Piece* dest_piece) { DCHECK(ShapeUtil::Equal(src_piece->subshape(), dest_piece->subshape())) << "src_piece has shape: " << ShapeUtil::HumanString(src_piece->subshape()) << "dest_piece has shape: " << ShapeUtil::HumanString(dest_piece->subshape()); dest_piece->set_array_value_state(src_piece->get_array_value_state()); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); Piece child_piece; child_piece.set_subshape(&subshape); CopyPieceSubtree(subshape, &src_piece->child(i), &child_piece); dest_piece->emplace_back(std::move(child_piece)); } } else if (shape.IsArray()) { dest_piece->set_buffer(const_cast<char*>(src_piece->buffer())); } } MutableLiteralBase::~MutableLiteralBase() = default; MutableBorrowingLiteral::MutableBorrowingLiteral( const MutableBorrowingLiteral& literal) : MutableLiteralBase() { shape_ = literal.shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.root_piece(), root_piece_); } MutableBorrowingLiteral& MutableBorrowingLiteral::operator=( const MutableBorrowingLiteral& literal) { shape_ = literal.shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.root_piece(), root_piece_); return *this; } MutableBorrowingLiteral::MutableBorrowingLiteral(MutableLiteralBase* literal) : MutableLiteralBase() { shape_ = literal->shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal->root_piece(), root_piece_); } MutableBorrowingLiteral::MutableBorrowingLiteral( MutableBorrowingLiteral literal, const ShapeIndex& view_root) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(literal.piece(view_root).subshape()); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.piece(view_root), root_piece_); } MutableBorrowingLiteral::MutableBorrowingLiteral(const char* src_buf_ptr, const Shape& shape) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(shape); CHECK(LayoutUtil::HasLayout(*shape_)); CHECK(!shape_->IsTuple()); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); root_piece_->set_buffer(const_cast<char*>(src_buf_ptr)); } MutableBorrowingLiteral::MutableBorrowingLiteral(absl::Span<char*> src_buf_ptrs, const Shape& shape) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(shape); if (!shape_->IsTuple()) { CHECK_EQ(src_buf_ptrs.size(), 1); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); root_piece_->set_buffer(const_cast<char*>(src_buf_ptrs[0])); } else { CHECK(!ShapeUtil::IsNestedTuple(*shape_)); CHECK_EQ(src_buf_ptrs.size(), ShapeUtil::TupleElementCount(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); for (int i = 0; i < src_buf_ptrs.size(); ++i) { Piece child_piece; const auto& src_shape = shape_->tuple_shapes(i); CHECK(src_shape.IsArray()); child_piece.set_subshape(&src_shape); child_piece.set_buffer(src_buf_ptrs[i]); root_piece_->emplace_back(std::move(child_piece)); } } } MutableBorrowingLiteral::MutableBorrowingLiteral(ShapeTree<char*> src_buf_ptrs) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(src_buf_ptrs.shape()); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); BuildPieceSubtree(*shape_, root_piece_); root_piece_->ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); } [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); MutableBorrowingLiteral::~MutableBorrowingLiteral() { if (root_piece_ != nullptr) { delete root_piece_; } } LiteralSlice::LiteralSlice(const LiteralBase& literal) : LiteralBase(), root_piece_(&literal.root_piece()) {} LiteralSlice::LiteralSlice(const LiteralBase& literal, const ShapeIndex& view_root) : LiteralBase(), root_piece_(&literal.piece(view_root)) {} BorrowingLiteral::BorrowingLiteral(const char* src_buf_ptr, const Shape& shape) : LiteralBase(), shape_(std::make_unique<Shape>(shape)) { CHECK(shape_->IsArray()); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); root_piece_.set_buffer(const_cast<char*>(src_buf_ptr)); } BorrowingLiteral::BorrowingLiteral(absl::Span<const char* const> src_buf_ptrs, const Shape& shape) : LiteralBase(), shape_(std::make_unique<Shape>(shape)) { CHECK(shape_->IsTuple()); CHECK(!ShapeUtil::IsNestedTuple(*shape_)); CHECK_EQ(src_buf_ptrs.size(), ShapeUtil::TupleElementCount(*shape_)); root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); BuildPieceSubtree(*shape_, &root_piece_); for (int i = 0, end = src_buf_ptrs.size(); i < end; ++i) { const auto& src_shape = shape_->tuple_shapes(i); CHECK(src_shape.IsArray()); root_piece_.child(i).set_buffer(const_cast<char*>(src_buf_ptrs[i])); } } BorrowingLiteral::BorrowingLiteral(ShapeTree<const char*> src_buf_ptrs) : LiteralBase(), shape_(std::make_unique<Shape>(src_buf_ptrs.shape())) { root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); BuildPieceSubtree(*shape_, &root_piece_); root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); } [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); });
#include "xla/literal.h" #include <algorithm> #include <cmath> #include <complex> #include <cstdint> #include <functional> #include <limits> #include <random> #include <string> #include <tuple> #include <utility> #include <vector> #include "absl/base/casts.h" #include "absl/hash/hash.h" #include "absl/random/random.h" #include "absl/status/status.h" #include "absl/strings/match.h" #include "absl/types/span.h" #include "xla/array.h" #include "xla/array2d.h" #include "xla/array3d.h" #include "xla/array4d.h" #include "xla/index_util.h" #include "xla/layout.h" #include "xla/layout_util.h" #include "xla/literal_util.h" #include "xla/primitive_util.h" #include "xla/shape.h" #include "xla/shape_tree.h" #include "xla/shape_util.h" #include "xla/test.h" #include "xla/types.h" #include "xla/util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/errors.h" #include "tsl/platform/logging.h" // IWYU pragma: keep #include "tsl/platform/macros.h" #include "tsl/platform/ml_dtypes.h" #include "tsl/platform/statusor.h" #include "tsl/platform/test_benchmark.h" class LiteralUtilTest : public ::testing::Test { protected: LiteralUtilTest() { Array4D<float> arr4d({ // clang-format off { // i0=0 { // i1=0 {1, 2, 3}, // i2=0 {4, 5, 6}, // i2=1 {7, 8, 9}, // i2=2 }, { // i1=1 {11, 12, 13}, {14, 15, 16}, {17, 18, 19}, }, }, { // i0=1 { // i1=0 {101, 102, 103}, {104, 105, 106}, {107, 108, 109}, }, { // i1=1 {201, 202, 203}, // i2=0 {204, 205, 206}, // i2=1 {207, 208, 209}, // i2=2 }, }, // clang-format on }); layout_r2_dim0major_ = LayoutUtil::MakeLayout({1, 0}); layout_r2_dim0minor_ = LayoutUtil::MakeLayout({0, 1}); layout_r3_dim0major_ = LayoutUtil::MakeLayout({2, 1, 0}); layout_r3_dim0minor_ = LayoutUtil::MakeLayout({0, 1, 2}); layout_r4_dim0major_ = LayoutUtil::MakeLayout({3, 2, 1, 0}); layout_r4_dim0minor_ = LayoutUtil::MakeLayout({0, 1, 2, 3}); literal_r4_2x2x3x3_dim0major_ = LiteralUtil::CreateR4FromArray4DWithLayout<float>(arr4d, layout_r4_dim0major_); literal_r4_2x2x3x3_dim0minor_ = LiteralUtil::CreateR4FromArray4DWithLayout<float>(arr4d, layout_r4_dim0minor_); } Layout layout_r2_dim0major_; Layout layout_r2_dim0minor_; Layout layout_r3_dim0major_; Layout layout_r3_dim0minor_; Layout layout_r4_dim0major_; Layout layout_r4_dim0minor_; Literal literal_r4_2x2x3x3_dim0major_; Literal literal_r4_2x2x3x3_dim0minor_; }; TEST_F(LiteralUtilTest, BroadcastVectorToMatrix1) { Literal literal = LiteralUtil::CreateR1<int64_t>({1, 2}); TF_ASSERT_OK_AND_ASSIGN( Literal broadcasted_literal, literal.Broadcast(/*result_shape=*/ShapeUtil::MakeShape(S64, {2, 2}), /*dimensions=*/{1})); EXPECT_EQ(broadcasted_literal, LiteralUtil::CreateR2<int64_t>({{1, 2}, {1, 2}})); }
LiteralUtilTest_C128Equality
xla/literal_test.cc
bool LiteralProtoHasValues(const LiteralProto& proto) { return !proto.s2s().empty() || !proto.s4s().empty() || !proto.s8s().empty() || !proto.s16s().empty() || proto.s32s_size() || proto.s64s_size() || !proto.u2s().empty() || !proto.u4s().empty() || !proto.u8s().empty() || !proto.u16s().empty() || proto.u32s_size() || proto.u64s_size() || !proto.f8e5m2s().empty() || !proto.f8e4m3fns().empty() || !proto.f8e4m3b11fnuzs().empty() || !proto.f8e5m2fnuzs().empty() || !proto.f8e4m3fnuzs().empty() || !proto.f16s().empty() || !proto.bf16s().empty() || proto.f32s_size() || proto.f64s_size() || proto.c64s_size() || proto.c128s_size() || proto.preds_size() || proto.tuple_literals_size(); } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { const Shape& NilShape() { static const Shape* shape = new Shape(TUPLE, {}, {}, {}); return *shape; } const Shape* TryInternShape(const Shape& shape) { if (shape.IsTuple() && shape.tuple_shapes_size() == 0) { return &NilShape(); } if (shape.IsArray() && shape.dimensions_size() == 0 && shape.is_static() && shape.layout().tiles_size() == 0 && shape.layout().memory_space() == 0) { return &ScalarShape(shape.element_type()); } return nullptr; } StrideConfig::StrideConfig(const Shape& source_shape, const Shape& dest_shape, absl::Span<const int64_t> dimensions) : dimensions(dimensions), base(dimensions.size(), 0), step(dimensions.size(), 1) { if (!dimensions.empty()) { // Selects the shape with the largest minor dimension as the one upon // which to run the tight stride loop. if (dimensions[LayoutUtil::Minor(source_shape.layout(), 0)] >= dimensions[LayoutUtil::Minor(dest_shape.layout(), 0)]) { minor_dimension = LayoutUtil::Minor(source_shape.layout(), 0); dest_stride = IndexUtil::GetDimensionStride(dest_shape, minor_dimension); } else { minor_dimension = LayoutUtil::Minor(dest_shape.layout(), 0); source_stride = IndexUtil::GetDimensionStride(source_shape, minor_dimension); } minor_loop_size = dimensions[minor_dimension]; step[minor_dimension] = minor_loop_size; } } LiteralBase::~LiteralBase() = default; const Shape& LiteralBase::shape() const { return root_piece().subshape(); } const char* LiteralBase::Piece::buffer() const { // std::visit is avoided here due to its code size issues. if (auto* r = std::get_if<DenseRep>(&rep_)) { return r->data; } if (auto* r = std::get_if<DenseInlinedRep>(&rep_)) { return r->data; } DCHECK(std::holds_alternative<TupleRep>(rep_) || std::holds_alternative<Uninitialized>(rep_)); return nullptr; } const LiteralBase::Piece& LiteralBase::piece( const ShapeIndex& shape_index) const { const Piece* piece = &root_piece(); for (const auto i : shape_index) { DCHECK_GE(i, 0); DCHECK_LT(i, piece->children_size()); piece = &piece->child(i); } return *piece; } std::ostream& operator<<(std::ostream& out, const Literal& literal) { out << literal.ToString(); return out; } Shape* MutableLiteralBase::mutable_shape_do_not_use() { const Shape* const_shape = shape_.get(); if (!shape_.OwnsPtr()) { shape_ = MaybeOwningShapePtr(std::make_unique<Shape>(*shape_)); } Shape* shape = shape_.get_mutable(); if (shape != const_shape) { std::function<void(const Shape&, Piece*)> set_piece_shapes = [&set_piece_shapes](const Shape& shape, Piece* piece) { piece->set_subshape(&shape); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); set_piece_shapes(subshape, &piece->child(i)); } } }; set_piece_shapes(*shape, &mutable_root_piece()); } return shape; } [&set_piece_shapes](const Shape& shape, Piece* piece) { piece->set_subshape(&shape); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); set_piece_shapes(subshape, &piece->child(i)); } } }; Literal::Literal() : Literal(NilShape()) {} Literal::Literal(const Shape& shape) : Literal(shape, /*allocate_arrays=*/true) {} void Literal::SetShape(const Shape& shape) { Shape shape_storage; const Shape* shape_ptr = &shape; if (LayoutUtil::HasCustomElementSizeInBits(shape)) { shape_storage = shape; shape_storage.mutable_layout()->set_element_size_in_bits(0); shape_ptr = &shape_storage; } if (const Shape* intered_shape_ptr = TryInternShape(*shape_ptr)) { shape_ = intered_shape_ptr; } else { shape_ = std::make_unique<Shape>(*shape_ptr); } } void Literal::SetPiece(const Shape& shape, Piece* piece, bool allocate_arrays, ArrayValueState leaf_array_value_state) { if (shape.IsTuple()) { for (const Shape& subshape : shape.tuple_shapes()) { Piece child_piece; child_piece.set_subshape(&subshape); SetPiece(subshape, &child_piece, allocate_arrays, leaf_array_value_state); piece->emplace_back(std::move(child_piece)); } } else if (shape.IsArray()) { DCHECK(LayoutUtil::IsDenseArray(shape)) << "literal array storage is currently only supported for dense " "arrays: " << shape; piece->set_array_value_state(leaf_array_value_state); if (leaf_array_value_state == LiteralBase::ArrayValueState::kKnown && allocate_arrays) { piece->AllocateBuffers(); } } } Literal::Literal(const Shape& shape, bool allocate_arrays, ArrayValueState leaf_array_value_state) : MutableLiteralBase() { SetShape(shape); CHECK(leaf_array_value_state != ArrayValueState::kKnown || LayoutUtil::HasLayout(*shape_)); root_piece_.set_subshape(shape_.get()); CHECK(&root_piece_.subshape() == shape_.get()); SetPiece(*shape_, &root_piece_, allocate_arrays, leaf_array_value_state); } Literal::~Literal() { DeallocateBuffers(); } void Literal::DeallocateBuffers() { root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { piece->DeallocateBuffers(); }); } Literal::Literal(Literal&& other) : MutableLiteralBase() { *this = std::move(other); } Literal& Literal::operator=(Literal&& other) { DCHECK(&other.root_piece_.subshape() == other.shape_.get()); using std::swap; swap(shape_, other.shape_); swap(root_piece_, other.root_piece_); DCHECK(&root_piece_.subshape() == shape_.get()); return *this; } Literal LiteralBase::CreateFromShape(const Shape& shape) { Literal literal(shape); literal.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (piece->subshape().IsArray()) { memset(piece->untyped_data(), 0, piece->size_bytes_dense()); } }); return literal; } [&](const ShapeIndex& index, Piece* piece) { if (piece->subshape().IsArray()) { memset(piece->untyped_data(), 0, piece->size_bytes_dense()); } }); Literal LiteralBase::CreateFromShapeWithUnknownLeafArrays(const Shape& shape) { Literal literal(shape, /*allocate_arrays=*/false, ArrayValueState::kUnknown); return literal; } Literal LiteralBase::CreateFromShapeWithUndeterminedLeafArrays( const Shape& shape) { Literal literal(shape, /*allocate_arrays=*/false, ArrayValueState::kUndetermined); return literal; } int32_t LiteralBase::GetDynamicSize(int64_t dim_index) const { return GetDynamicSize(dim_index, {}); } int32_t LiteralBase::GetDynamicSize(int64_t dim_index, const ShapeIndex& shape_index) const { return piece(shape_index).GetDynamicSize(dim_index); } std::optional<int64_t> LiteralBase::GetFirstInteger() const { if (!primitive_util::IsIntegralType(shape().element_type())) { return std::nullopt; } return primitive_util::IntegralTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, void LiteralBase::BuildPieceSubtree(const Shape& shape, Piece* piece) { CHECK(shape.IsTuple()); for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); Piece child_piece; child_piece.set_subshape(&subshape); if (subshape.IsTuple()) { BuildPieceSubtree(subshape, &child_piece); } piece->emplace_back(std::move(child_piece)); } } absl::Status LiteralBase::SerializeToString(std::string* output) const { ShapeProto shape_proto = shape().ToProto(); TF_ASSIGN_OR_RETURN(int64_t size, ShapeUtil::SerializedSizeWithProto(shape(), shape_proto)); output->resize(size); return SerializeWithShapeProto(shape_proto, output->data()); } absl::StatusOr<std::string> LiteralBase::SerializeAsString() const { std::string result; TF_RETURN_IF_ERROR(SerializeToString(&result)); return std::move(result); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { void MutableLiteralBase::CopyElementFrom(const LiteralSlice& src_literal, absl::Span<const int64_t> src_index, absl::Span<const int64_t> dest_index) { DCHECK(LayoutUtil::IsDenseArray(shape())); DCHECK_EQ(shape().element_type(), src_literal.shape().element_type()); const int64_t src_linear_index = IndexUtil::MultidimensionalIndexToLinearIndex(src_literal.shape(), src_index); const int64_t dest_linear_index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), dest_index); const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); char* dest_address = static_cast<char*>(untyped_data()) + dest_linear_index * primitive_size; const char* source_address = static_cast<const char*>(src_literal.untyped_data()) + src_linear_index * primitive_size; if (dest_address != source_address) { memcpy(dest_address, source_address, primitive_size); } } /* static */ absl::StatusOr<Literal> MutableLiteralBase::CreateFromProto( const LiteralProto& proto, bool prohibit_empty_literal) { if (!proto.has_shape()) { return InvalidArgument("LiteralProto has no shape"); } Shape shape(proto.shape()); if (ShapeUtil::HasPrimitiveType(shape, OPAQUE_TYPE)) { return InvalidArgument( "Literal shape cannot include OPAQUE_TYPE sub-shape"); } if (!LayoutUtil::HasLayout(shape)) { return InvalidArgument("LiteralProto has no layout"); } if (LayoutUtil::IsSparseArray(shape)) { return Unimplemented("Sparse literals are not supported"); } TF_RETURN_IF_ERROR(ShapeUtil::ValidateShapeWithOptionalLayout(shape)); Literal literal(shape); TF_RETURN_IF_ERROR(literal.root_piece_.ForEachMutableSubpieceWithStatus( [&](const ShapeIndex& index, Piece* piece) -> absl::Status { const LiteralProto* proto_element = &proto; for (int64_t i : index) { CHECK(i < proto_element->tuple_literals_size()); proto_element = &proto_element->tuple_literals(i); } if (piece->subshape().IsTuple()) { if (proto_element->tuple_literals_size() != ShapeUtil::TupleElementCount(piece->subshape())) { return InvalidArgument( "Expected %d tuple elements in LiteralProto, has %d", ShapeUtil::TupleElementCount(piece->subshape()), proto_element->tuple_literals_size()); } return absl::OkStatus(); } if (piece->subshape().element_type() == TOKEN) { return absl::OkStatus(); } CHECK(piece->subshape().IsArray()); // When prohibit_empty_literal is false (allowing literal with no // values), only copy from proto if the literal proto has values. This // mode is used for a learned cost model. if (prohibit_empty_literal || LiteralProtoHasValues(*proto_element)) { TF_RETURN_IF_ERROR(piece->CopyFromProto(*proto_element)); } return absl::OkStatus(); })); return std::move(literal); } TF_RETURN_IF_ERROR(literal.root_piece_.ForEachMutableSubpieceWithStatus( Literal Literal::SubLiteral(ShapeIndexView shape_index) { if (!shape_index.empty()) { auto decomposed = this->DecomposeTuple(); return decomposed.at(shape_index.front()) .SubLiteral(shape_index.subspan(1)); } else { return std::move(*this); } } std::vector<Literal> Literal::DecomposeTuple() { CHECK(shape().IsTuple()); std::vector<Literal> elements; const auto tuple_element_count = ShapeUtil::TupleElementCount(shape()); elements.reserve(tuple_element_count); for (int i = 0; i < tuple_element_count; ++i) { elements.push_back(Literal(ShapeUtil::GetSubshape(shape(), {i}), /*allocate_arrays=*/false)); Literal& element = elements.back(); element.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* dest_piece) { if (dest_piece->subshape().IsTuple()) { return; } ShapeIndex src_index = {i}; for (int64_t j : index) { src_index.push_back(j); } Piece& src_piece = piece(src_index); // Move the respective buffer over to the element Literal. dest_piece->MoveDataFrom(src_piece); }); } // Set this literal to be nil-shaped. *this = Literal(); return elements; } [&](const ShapeIndex& index, Piece* dest_piece) { if (dest_piece->subshape().IsTuple()) { return; } ShapeIndex src_index = {i}; for (int64_t j : index) { src_index.push_back(j); } Piece& src_piece = piece(src_index); // Move the respective buffer over to the element Literal. dest_piece->MoveDataFrom(src_piece); }); void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } int32_t LiteralBase::Piece::GetDynamicSize(int64_t dim_index) const { CHECK(LayoutUtil::IsDenseArray(subshape())); if (!subshape_->is_dynamic_dimension(dim_index)) { // This is a static dimension, return size. return subshape_->dimensions(dim_index); } return dynamic_size_buffer()[dim_index]; } void LiteralBase::Piece::SetDynamicSize(int64_t dim_index, int32_t size) { CHECK(LayoutUtil::IsDenseArray(subshape())); CHECK(subshape_->is_dynamic_dimension(dim_index)); dynamic_size_buffer()[dim_index] = size; } void LiteralBase::Piece::AllocateBuffers() { const int64_t bytes = total_bytes_dense(); if (bytes > kMaxInlinedBytes) { CHECK_EQ(buffer(), nullptr); rep_.emplace<DenseRep>(); set_buffer( static_cast<char*>(tsl::port::AlignedMalloc(bytes, kMinimumAlignment))); } else { rep_.emplace<DenseInlinedRep>(); } } void LiteralBase::Piece::DeallocateBuffers() { if (auto* array_rep = GetDenseRep()) { tsl::port::AlignedFree(array_rep->data); rep_.emplace<Uninitialized>(); } } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } absl::Status LiteralBase::Piece::CopyFrom(const LiteralBase::Piece& src, bool only_dynamic_bound) { CHECK(subshape_ != nullptr); CHECK(src.subshape_ != nullptr); CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK(LayoutUtil::IsDenseArray(src.subshape())) << __func__ << " is only supported for dense arrays: " << src.subshape(); if (!only_dynamic_bound) { CHECK(ShapeUtil::Compatible(subshape(), src.subshape())); } if (src.array_value_state_ == ArrayValueState::kUnknown || src.array_value_state_ == ArrayValueState::kUndetermined) { if (array_value_state_ == ArrayValueState::kKnown) { DeallocateBuffers(); } array_value_state_ = src.array_value_state_; return absl::OkStatus(); } else { CHECK(src.array_value_state_ == ArrayValueState::kKnown); if (array_value_state_ == ArrayValueState::kUndetermined || array_value_state_ == ArrayValueState::kUnknown) { AllocateBuffers(); } array_value_state_ = src.array_value_state_; } if (ShapeUtil::Equal(subshape(), src.subshape())) { // If the layouts are equal it's faster just to memcpy. memcpy(buffer(), src.buffer(), src.size_bytes_dense()); } else { std::vector<int64_t> origin(subshape().rank(), 0); primitive_util::ArrayTypeSwitch<void>( [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, subshape().element_type()); } DCHECK_EQ(dynamic_size_buffer_bytes(), src.dynamic_size_buffer_bytes()); if (subshape().is_dynamic() && src.subshape().is_dynamic()) { memcpy(dynamic_size_buffer(), src.dynamic_size_buffer(), src.dynamic_size_buffer_bytes()); } return absl::OkStatus(); } [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, void MutableLiteralBase::SetDynamicSize(int64_t dim_index, int32_t size) { return SetDynamicSize(dim_index, {}, size); } void MutableLiteralBase::SetDynamicSize(int64_t dim_index, const ShapeIndex& shape_index, int32_t size) { Shape* subshape = ShapeUtil::GetMutableSubshape(mutable_shape_do_not_use(), shape_index); CHECK(LayoutUtil::IsDenseArray(*subshape)) << __func__ << " is only supported for dense arrays: " << *subshape; CHECK_GE(subshape->dimensions(dim_index), size); subshape->set_dynamic_dimension(dim_index, true); CHECK_EQ(&piece(shape_index).subshape(), subshape); piece(shape_index).SetDynamicSize(dim_index, size); } absl::Status MutableLiteralBase::CopyFrom(const LiteralSlice& src_literal, const ShapeIndex& dest_shape_index, const ShapeIndex& src_shape_index, bool only_dynamic_bound) { const Shape& dest_subshape = ShapeUtil::GetSubshape(shape(), dest_shape_index); const Shape& src_subshape = ShapeUtil::GetSubshape(src_literal.shape(), src_shape_index); if (only_dynamic_bound) { auto& bound_shape = dest_subshape.is_static() ? src_subshape : dest_subshape; auto& compact_shape = dest_subshape.is_static() ? dest_subshape : src_subshape; CHECK(ShapeUtil::DynamicShapeIsCompatible(compact_shape, bound_shape)) << compact_shape.ToString() << " vs " << bound_shape.ToString(); } else { if (!ShapeUtil::Compatible(dest_subshape, src_subshape)) { return InvalidArgument( "Destination subshape incompatible with source subshape: %s vs %s", ShapeUtil::HumanString(dest_subshape), ShapeUtil::HumanString(src_subshape)); } } return mutable_root_piece().ForEachMutableSubpieceWithStatus( [&](const ShapeIndex& index, Piece* piece) { if (!piece->subshape().IsArray()) { return absl::OkStatus(); } // Determine if this index is in the part of this literal that we want // to copy over from src_literal. bool in_subtree_to_copy = true; for (int i = 0; i < dest_shape_index.size(); ++i) { if (index[i] != dest_shape_index[i]) { in_subtree_to_copy = false; break; } } if (!in_subtree_to_copy) { return absl::OkStatus(); } // Construct the index of the corresponding piece in the source literal. ShapeIndex src_piece_index = src_shape_index; for (int64_t i = dest_shape_index.size(), end = index.size(); i < end; ++i) { src_piece_index.push_back(index[i]); } TF_RETURN_IF_ERROR( piece->CopyFrom(src_literal.piece(src_piece_index), /*only_dynamic_bound=*/only_dynamic_bound)); return absl::OkStatus(); }); } [&](const ShapeIndex& index, Piece* piece) { if (!piece->subshape().IsArray()) { return absl::OkStatus(); } // Determine if this index is in the part of this literal that we want // to copy over from src_literal. bool in_subtree_to_copy = true; for (int i = 0; i < dest_shape_index.size(); ++i) { if (index[i] != dest_shape_index[i]) { in_subtree_to_copy = false; break; } } if (!in_subtree_to_copy) { return absl::OkStatus(); } // Construct the index of the corresponding piece in the source literal. ShapeIndex src_piece_index = src_shape_index; for (int64_t i = dest_shape_index.size(), end = index.size(); i < end; ++i) { src_piece_index.push_back(index[i]); } TF_RETURN_IF_ERROR( piece->CopyFrom(src_literal.piece(src_piece_index), /*only_dynamic_bound=*/only_dynamic_bound)); return absl::OkStatus(); }); absl::Status Literal::MoveFrom(Literal&& src_literal, const ShapeIndex& dest_shape_index) { const Shape& dest_subshape = ShapeUtil::GetSubshape(shape(), dest_shape_index); if (!ShapeUtil::Equal(dest_subshape, src_literal.shape())) { return InvalidArgument( "Destination subshape not equal to source shape: %s vs %s", ShapeUtil::HumanString(dest_subshape), ShapeUtil::HumanString(src_literal.shape())); } src_literal.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& src_index, Piece* src_piece) { if (!src_piece->subshape().IsArray()) { return; } ShapeIndex dest_index = dest_shape_index; for (int64_t i : src_index) { dest_index.push_back(i); } Piece& dest_piece = piece(dest_index); dest_piece.DeallocateBuffers(); dest_piece.MoveDataFrom(*src_piece); }); src_literal.shape_ = MaybeOwningShapePtr(&NilShape()); src_literal.root_piece_ = Piece(); src_literal.root_piece_.set_subshape(src_literal.shape_.get()); return absl::OkStatus(); } [&](const ShapeIndex& src_index, Piece* src_piece) { if (!src_piece->subshape().IsArray()) { return; } ShapeIndex dest_index = dest_shape_index; for (int64_t i : src_index) { dest_index.push_back(i); } Piece& dest_piece = piece(dest_index); dest_piece.DeallocateBuffers(); dest_piece.MoveDataFrom(*src_piece); }); absl::Status MutableLiteralBase::CopySliceFrom( const LiteralSlice& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << shape(); TF_RET_CHECK(LayoutUtil::IsDenseArray(src_literal.shape())) << src_literal.shape(); TF_RET_CHECK(ShapeUtil::SameElementType(src_literal.shape(), shape())); TF_RET_CHECK(src_literal.shape().rank() == src_base.size()); TF_RET_CHECK(shape().rank() == dest_base.size()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, void MutableLiteralBase::PopulateR1(const tsl::core::Bitmap& values) { CHECK(shape().IsArray()); CHECK_EQ(shape().rank(), 1); CHECK_EQ(element_count(), values.bits()); CHECK_EQ(shape().element_type(), PRED); for (int64_t i = 0; i < static_cast<int64_t>(values.bits()); ++i) { Set({i}, values.get(i)); } } void MutableLiteralBase::PopulateInplaceInternal( absl::FunctionRef<void(void*, absl::Span<const int64_t>, int)> populator, bool parallel) { const Shape& this_shape = shape(); const int64_t rank = this_shape.rank(); DCHECK(LayoutUtil::IsDenseArray(this_shape)); char* const dest_base = static_cast<char*>(untyped_data()); if (rank > 0) { StrideConfig stride_config(this_shape, this_shape, this_shape.dimensions()); const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); const int64_t num_elements = ShapeUtil::ElementsIn(shape()); // If we are rank-1 and we are `parallel`, it is better to use a smaller // `step` than what `StrideConfig` does: stick the entire dimension in the // inner-most loop. if (parallel && this_shape.rank() == 1) { const int64_t thread_count = ShapeUtil::GetForEachIndexParallelThreadCount(); // Let's just divide up the array into small amounts per thread. stride_config.dest_stride = stride_config.minor_loop_size = num_elements > 32 ? std::max<int64_t>(num_elements / thread_count, 1) : num_elements; stride_config.step = {stride_config.minor_loop_size}; } auto init_function = [&](absl::Span<const int64_t> indexes, int thread_id) -> absl::StatusOr<bool> { const int64_t index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), indexes); DimensionVector minor_scan_indexes(rank, 0); std::copy(indexes.begin(), indexes.end(), minor_scan_indexes.begin()); char* dest_ptr = dest_base + index * primitive_size; char* const dest_end = dest_base + // This handles the case where minor_loop_size does not evenly divide // the most minor dimension. std::min(index + stride_config.minor_loop_size, num_elements) * primitive_size; while (dest_ptr < dest_end) { populator(dest_ptr, minor_scan_indexes, thread_id); ++minor_scan_indexes[stride_config.minor_dimension]; dest_ptr += primitive_size; } return true; }; if (parallel) { ShapeUtil::ForEachIndexParallel(this_shape, stride_config.base, stride_config.dimensions, stride_config.step, init_function); } else { ShapeUtil::ForEachIndex( this_shape, stride_config.base, stride_config.dimensions, stride_config.step, [&init_function]( absl::Span<const int64_t> indexes) -> absl::StatusOr<bool> { auto result_ignored = init_function(indexes, /*thread_id=*/-1); return true; }); } } else { // For scalars. populator(dest_base, {}, /*thread_id=*/-1); } } auto init_function = [&](absl::Span<const int64_t> indexes, int thread_id) -> absl::StatusOr<bool> { const int64_t index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), indexes); DimensionVector minor_scan_indexes(rank, 0); std::copy(indexes.begin(), indexes.end(), minor_scan_indexes.begin()); char* dest_ptr = dest_base + index * primitive_size; char* const dest_end = dest_base + // This handles the case where minor_loop_size does not evenly divide // the most minor dimension. std::min(index + stride_config.minor_loop_size, num_elements) * primitive_size; while (dest_ptr < dest_end) { populator(dest_ptr, minor_scan_indexes, thread_id); ++minor_scan_indexes[stride_config.minor_dimension]; dest_ptr += primitive_size; } return true; }; [&init_function]( absl::Span<const int64_t> indexes) -> absl::StatusOr<bool> { auto result_ignored = init_function(indexes, /*thread_id=*/-1); return true; }); absl::Status MutableLiteralBase::PopulateInplace( absl::FunctionRef<void(void*, absl::Span<const int64_t>)> populator) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); PopulateInplaceInternal( [&](void* dest, absl::Span<const int64_t> indexes, int /*thread_id*/) { return populator(dest, indexes); }, /*parallel=*/false); return absl::OkStatus(); } absl::Status MutableLiteralBase::PopulateInplaceParallel( absl::FunctionRef<void(void*, absl::Span<const int64_t>, int)> populator) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); PopulateInplaceInternal(populator, /*parallel=*/element_count() > 32); return absl::OkStatus(); } Literal LiteralBase::Relayout(const Layout& new_layout, const ShapeIndex& shape_index) const { // Create new shape with 'new_layout' set at the given shape index. Shape new_shape = shape(); Shape* subshape = ShapeUtil::GetMutableSubshape(&new_shape, shape_index); TF_CHECK_OK(LayoutUtil::ValidateLayoutForShape(new_layout, *subshape)); *subshape->mutable_layout() = new_layout; // LINT.IfChange // s4 literals are stored in uint8_t/int8_t, therefore element_size_in_bits // must be removed. if (subshape->layout().element_size_in_bits() == 4) { subshape->mutable_layout()->set_element_size_in_bits(0); } // LINT.ThenChange(//tensorflow/compiler/xla/types.h) Literal result(new_shape); TF_CHECK_OK(result.CopyFrom(*this)); return result; } Literal LiteralBase::Relayout(const Shape& shape_with_layout) const { CHECK(ShapeUtil::Compatible(shape_with_layout, shape())) << "Given shape_with_layout " << ShapeUtil::HumanString(shape_with_layout) << " not compatible with literal shape " << ShapeUtil::HumanString(shape()); Literal result = CreateFromShape(shape_with_layout); ShapeUtil::ForEachSubshape( result.shape(), [this, &result](const Shape& subshape, const ShapeIndex& index) { if (subshape.IsArray()) { TF_CHECK_OK(result.CopyFrom(*this, /*dest_shape_index=*/index, /*src_shape_index=*/index)); } }); return result; } [this, &result](const Shape& subshape, const ShapeIndex& index) { if (subshape.IsArray()) { TF_CHECK_OK(result.CopyFrom(*this, /*dest_shape_index=*/index, /*src_shape_index=*/index)); } }); Literal LiteralBase::ToBoundedDynamic(const Shape& bounded_shape) const { CHECK(bounded_shape.is_dynamic()); Literal result(bounded_shape); ShapeUtil::ForEachSubshape( shape(), [&](const Shape& subshape, const ShapeIndex& index) { if (!subshape.IsArray()) { return; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (bounded_shape.is_dynamic_dimension(i)) { result.SetDynamicSize(i, subshape.dimensions(i)); } } }); TF_CHECK_OK(result.CopyFrom(*this, {}, {}, /*only_dynamic_bound=*/true)); return result; } shape(), [&](const Shape& subshape, const ShapeIndex& index) { if (!subshape.IsArray()) { return; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (bounded_shape.is_dynamic_dimension(i)) { result.SetDynamicSize(i, subshape.dimensions(i)); } } }); Literal LiteralBase::ToStatic() const { // Create new shape with 'new_layout' set at the given shape index. Shape new_shape = shape(); ShapeUtil::ForEachMutableSubshape( &new_shape, [this](Shape* subshape, const ShapeIndex& index) { if (!subshape->IsArray()) { return; } for (int64_t i = 0; i < subshape->rank(); ++i) { // GetDynamicSize has a 32-bit return type and may truncate static // dimensions, so make sure to skip. if (!subshape->is_dynamic_dimension(i)) continue; subshape->set_dynamic_dimension(i, false); subshape->set_dimensions(i, GetDynamicSize(i, index)); } }); Literal result(new_shape); TF_CHECK_OK(result.CopyFrom(*this, {}, {}, /*only_dynamic_bound=*/true)); return result; } &new_shape, [this](Shape* subshape, const ShapeIndex& index) { if (!subshape->IsArray()) { return; } for (int64_t i = 0; i < subshape->rank(); ++i) { // GetDynamicSize has a 32-bit return type and may truncate static // dimensions, so make sure to skip. if (!subshape->is_dynamic_dimension(i)) continue; subshape->set_dynamic_dimension(i, false); subshape->set_dimensions(i, GetDynamicSize(i, index)); } }); absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { absl::StatusOr<Literal> LiteralBase::Broadcast( const Shape& result_shape, absl::Span<const int64_t> dimensions) const { const LiteralBase& src = *this; const Shape& src_shape = shape(); if (!src_shape.IsArray()) { return InvalidArgument("Broadcast only supports arrays."); } const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(src_shape.element_type()); switch (primitive_size) { case 0: return BroadcastHelper<0>(src, src_shape, result_shape, dimensions); case 1: return BroadcastHelper<1>(src, src_shape, result_shape, dimensions); case 2: return BroadcastHelper<2>(src, src_shape, result_shape, dimensions); case 4: return BroadcastHelper<4>(src, src_shape, result_shape, dimensions); case 8: return BroadcastHelper<8>(src, src_shape, result_shape, dimensions); case 16: return BroadcastHelper<16>(src, src_shape, result_shape, dimensions); default: LOG(FATAL) << "Unhandled primitive size " << primitive_size; return InvalidArgument("Unhandled primitive size"); break; } } absl::StatusOr<Literal> LiteralBase::Reshape( absl::Span<const int64_t> dimensions) const { if (!LayoutUtil::IsDenseArray(shape())) { return InvalidArgument("Reshape is only supported for dense arrays."); } if (shape().is_dynamic()) { // TODO(b/243182930): We should consider supporting dynamic reshape. return Unimplemented("Dynamic reshape is not implemented."); } Literal output; if (!LayoutUtil::IsMonotonicWithDim0Major(shape().layout())) { output = Relayout(LayoutUtil::GetDefaultLayoutForRank(shape().rank())); } else { output = Clone(); } // Because the layout is monotonic, we can simply reuse the same sequence of // values without changing their order. *output.mutable_shape_do_not_use() = ShapeUtil::MakeShape(shape().element_type(), dimensions); int64_t elements_before = ShapeUtil::ElementsIn(shape()); int64_t elements_after = ShapeUtil::ElementsIn(output.shape()); if (elements_before != elements_after) { return InvalidArgument( "Shapes before and after Literal::Reshape have different numbers " "of elements: %s vs %s.", ShapeUtil::HumanString(shape()), ShapeUtil::HumanString(output.shape())); } return std::move(output); } Literal LiteralBase::Transpose(absl::Span<const int64_t> permutation) const { CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); CHECK(shape().rank() == permutation.size() && IsPermutation(permutation)) << "Given permutation is not a permutation of dimension numbers"; // To transpose the array, we just permute the dimensions and layout, and // do a straight memory copy of the raw data set. // This is considerably faster than iterating over every array element using // the EachCell<>() and Set<>() APIs. Shape permuted_shape = ShapeUtil::PermuteDimensions(permutation, shape()); // Replace the layout with one affine to this shape, such that a // transpose operation can be performed by leaving the flat values // representation intact. // For example, consider the shape F32[11,8]{1,0} under a {1,0} permutation. // The shape with affine layout resulting from that operation will be // F32[8,11]{0,1}, since it leaves the original most minor (the 8 sized), the // most minor. // // Essentially, given MinMaj(Di) the position of the Di dimension within the // minor to major vector, and given T(Di) the index that the original Di // dimension has within the transposed array, a layout is affine if // MinMaj(Di) == TMinMaj(T(Di)), with TMinMaj() being the minor to major // vector of the affine layout. std::vector<int64_t> inverse_permutation = InversePermutation(permutation); CHECK(LayoutUtil::IsDenseArray(permuted_shape)); Layout* layout = permuted_shape.mutable_layout(); layout->clear_minor_to_major(); for (auto index : LayoutUtil::MinorToMajor(shape())) { layout->add_minor_to_major(inverse_permutation[index]); } Literal new_literal(permuted_shape); if (shape().is_dynamic()) { for (int64_t i = 0; i < shape().rank(); i++) { if (shape().is_dynamic_dimension(i)) { // Set the dynamic size of any dynamic dimension in the transposed // literal. new_literal.SetDynamicSize(inverse_permutation[i], GetDynamicSize(i)); } } } DCHECK_EQ(ShapeUtil::ByteSizeOf(new_literal.shape()), ShapeUtil::ByteSizeOf(shape())); std::memcpy(new_literal.untyped_data(), untyped_data(), size_bytes()); return new_literal; } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( Literal LiteralBase::Slice(absl::Span<const int64_t> start_indices, absl::Span<const int64_t> limit_indices) const { CHECK(shape().IsArray()) << "tuple is not supported for slice"; DimensionVector result_dimensions; for (int64_t dnum = 0; dnum < shape().rank(); ++dnum) { CHECK_GE(start_indices[dnum], 0); CHECK_LE(limit_indices[dnum], shape().dimensions(dnum)) << "dnum = " << dnum; int64_t dimension = limit_indices[dnum] - start_indices[dnum]; CHECK_GE(dimension, 0) << "dnum = " << dnum; result_dimensions.push_back(dimension); } auto result_shape = ShapeUtil::MakeShapeWithDenseLayout( shape().element_type(), result_dimensions, LayoutUtil::MinorToMajor(shape())); ShapeUtil::CopyDynamicDimensions(&result_shape, shape()); Literal result_literal(result_shape); primitive_util::ArrayTypeSwitch<void>( [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; return SliceInternal<NativeT>(*this, start_indices, result_literal); }, result_shape.element_type()); return result_literal; } Literal LiteralBase::Clone() const { Literal result(shape()); TF_CHECK_OK(result.CopyFrom(*this)); return result; } std::unique_ptr<Literal> LiteralBase::CloneToUnique() const { auto result = std::make_unique<Literal>(shape()); TF_CHECK_OK(result->CopyFrom(*this)); return result; } bool LiteralBase::IsDetermined(const ShapeIndex& shape_index) const { return piece(shape_index).IsDetermined(); } bool LiteralBase::IsKnown(const ShapeIndex& shape_index) const { return piece(shape_index).IsKnown(); } std::string LiteralBase::GetAsString(absl::Span<const int64_t> multi_index, const ShapeIndex& shape_index) const { const Shape& subshape = ShapeUtil::GetSubshape(shape(), shape_index); CHECK(LayoutUtil::IsDenseArray(subshape)); return primitive_util::ArrayTypeSwitch<std::string>( [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, subshape.element_type()); } [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, std::optional<int64_t> LiteralBase::GetIntegralAsS64( absl::Span<const int64_t> multi_index) const { CHECK(LayoutUtil::IsDenseArray(shape())); return primitive_util::PrimitiveTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, std::optional<double> LiteralBase::GetAsDouble( absl::Span<const int64_t> multi_index) const { const Shape& s = shape(); CHECK(LayoutUtil::IsDenseArray(s)); return primitive_util::PrimitiveTypeSwitch<std::optional<double>>( [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, s.element_type()); } [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, std::optional<double> LiteralBase::GetSumAsDouble( absl::Span<const int64_t> linear_indices) const { const Shape& s = shape(); CHECK(LayoutUtil::IsDenseArray(s)); if (!primitive_util::IsFloatingPointType(s.element_type())) { return std::nullopt; } return primitive_util::FloatingPointTypeSwitch<double>( [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, s.element_type()); } [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, std::optional<complex128> LiteralBase::GetAsComplex128( absl::Span<const int64_t> multi_index) const { return primitive_util::PrimitiveTypeSwitch<std::optional<complex128>>( [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, absl::Status MutableLiteralBase::SetIntegralAsS64( absl::Span<const int64_t> multi_index, int64_t value) { CHECK(LayoutUtil::IsDenseArray(shape())); return primitive_util::PrimitiveTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, absl::Status MutableLiteralBase::SetFromDouble( absl::Span<const int64_t> multi_index, double value) { CHECK(LayoutUtil::IsDenseArray(shape())); if (!primitive_util::IsFloatingPointType(shape().element_type())) { return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); } primitive_util::FloatingPointTypeSwitch<void>( [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, shape().element_type()); return absl::OkStatus(); } [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, void PrintShape(bool print_layout, const Shape& shape, Printer* printer) { if (print_layout) { ShapeUtil::PrintHumanStringWithLayout(printer, shape); } else { ShapeUtil::PrintHumanString(printer, shape); } } void TuplePrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); printer->Append(oneline ? "( " : "(\n"); for (int i = 0; i < ShapeUtil::TupleElementCount(subshape); ++i) { ShapeIndex element_index = shape_index; element_index.push_back(i); if (i > 0) printer->Append(oneline ? ", " : ",\n"); PrintHelper(literal, element_index, print_shape, print_layout, oneline, printer); } printer->Append(oneline ? " )" : "\n)"); } void DenseArrayPrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); int64_t rank = subshape.rank(); const absl::string_view linebreak = oneline ? " " : "\n"; std::function<void(absl::Span<const int64_t> dimensions, std::vector<int64_t>*)> print_recursive = [&](absl::Span<const int64_t> dimensions, std::vector<int64_t>* accum_indices) { // dimensions.size() decreases by 1 at each recursive call, // and accum_indices->size() increases by 1. // Their sum is equal to the rank of the tensor. CHECK_EQ(rank, dimensions.size() + accum_indices->size()); auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; if (dimensions.empty()) { // Display predicates as 0s and 1s so that the string is more dense. std::string elem; if (subshape.element_type() == PRED && rank > 0) { elem = literal.Get<bool>(*accum_indices, shape_index) ? "1" : "0"; } else { elem = literal.GetAsString(*accum_indices, shape_index); } printer->Append(elem); } else { printer->Append(brace_to_string("{")); for (int i = 0; i < dimensions[0]; ++i) { accum_indices->push_back(i); print_recursive(dimensions.subspan(1), accum_indices); accum_indices->pop_back(); if (i < dimensions[0] - 1) { printer->Append(","); printer->Append(dimensions.size() > 1 ? linebreak : " "); } } printer->Append(brace_to_string("}")); } }; if (print_shape) { PrintShape(print_layout, subshape, printer); if (subshape.is_dynamic()) { printer->Append("("); for (int64_t i = 0; i < subshape.dimensions_size(); ++i) { printer->Append(literal.GetDynamicSize(i, shape_index)); if (i < subshape.dimensions_size() - 1) { printer->Append(","); } } printer->Append(")"); } printer->Append(" "); } std::vector<int64_t> indices = {}; std::vector<int64_t> dimensions; dimensions.reserve(subshape.rank()); for (int64_t i = 0; i < subshape.rank(); ++i) { dimensions.push_back(literal.GetDynamicSize(i, shape_index)); } print_recursive(dimensions, &indices); } print_recursive = [&](absl::Span<const int64_t> dimensions, std::vector<int64_t>* accum_indices) { // dimensions.size() decreases by 1 at each recursive call, // and accum_indices->size() increases by 1. // Their sum is equal to the rank of the tensor. CHECK_EQ(rank, dimensions.size() + accum_indices->size()); auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; if (dimensions.empty()) { // Display predicates as 0s and 1s so that the string is more dense. std::string elem; if (subshape.element_type() == PRED && rank > 0) { elem = literal.Get<bool>(*accum_indices, shape_index) ? "1" : "0"; } else { elem = literal.GetAsString(*accum_indices, shape_index); } printer->Append(elem); } else { printer->Append(brace_to_string("{")); for (int i = 0; i < dimensions[0]; ++i) { accum_indices->push_back(i); print_recursive(dimensions.subspan(1), accum_indices); accum_indices->pop_back(); if (i < dimensions[0] - 1) { printer->Append(","); printer->Append(dimensions.size() > 1 ? linebreak : " "); } } printer->Append(brace_to_string("}")); } }; auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; void PrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); CHECK(LayoutUtil::HasLayout(literal.shape())); CHECK(LayoutUtil::HasLayout(subshape)); if (subshape.IsTuple()) { TuplePrintHelper(literal, shape_index, print_shape, print_layout, oneline, printer); } else if (subshape.IsToken()) { printer->Append("token"); } else { CHECK(LayoutUtil::IsDenseArray(subshape)); if (literal.IsKnown(shape_index)) { DenseArrayPrintHelper(literal, shape_index, print_shape, print_layout, oneline, printer); } else { PrintShape(print_layout, subshape, printer); printer->Append(" "); if (literal.IsDetermined(shape_index)) { printer->Append("unknown"); } else { printer->Append("undetermined"); } } } } void LiteralBase::Print(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/false, /*oneline=*/false, printer); } void LiteralBase::PrintOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/false, /*oneline=*/true, printer); } void LiteralBase::PrintWithoutShape(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/false, /*print_layout=*/false, /*oneline=*/false, printer); } void LiteralBase::PrintWithoutShapeOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/false, /*print_layout=*/false, /*oneline=*/true, printer); } void LiteralBase::PrintWithLayout(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/true, /*oneline=*/false, printer); } void LiteralBase::PrintWithLayoutOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/true, /*oneline=*/true, printer); } std::string LiteralBase::ToString() const { StringPrinter printer; Print(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringOneline() const { StringPrinter printer; PrintOneline(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithoutShape() const { StringPrinter printer; PrintWithoutShape(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithoutShapeOneline() const { StringPrinter printer; PrintWithoutShapeOneline(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithLayout() const { StringPrinter printer; PrintWithLayout(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithLayoutOneline() const { StringPrinter printer; PrintWithLayoutOneline(&printer); return std::move(printer).ToString(); } void LiteralBase::EachCellAsString( absl::FunctionRef<void(absl::Span<const int64_t> indices, const std::string& value)> per_cell) const { if (ShapeUtil::IsZeroElementArray(shape())) { return; } auto indices = IndexUtil::LinearIndexToMultidimensionalIndex( shape(), /*linear_index=*/0); do { per_cell(indices, GetAsString(indices)); } while (IndexUtil::BumpIndices(shape(), absl::MakeSpan(indices))); } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { absl::StatusOr<Literal> ConvertSwitch(const LiteralBase& literal, PrimitiveType primitive_dest_type) { TF_RET_CHECK(LayoutUtil::IsDenseArray(literal.shape())); if (literal.shape().element_type() == primitive_dest_type) { return literal.Clone(); } // Source Array type requirement is ensured by IsDenseArray before. if (!primitive_util::IsArrayType(primitive_dest_type) || !primitive_util::IsArrayType(literal.shape().element_type())) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(literal.shape().element_type()), PrimitiveType_Name(primitive_dest_type)); } // At this point, we know both src & dst are array types, while src is not // complex type, so we can allocate the result literal here to avoid // duplicating it N^2 times in the conversion implementation. Literal result( ShapeUtil::ChangeElementType(literal.shape(), primitive_dest_type)); TF_RETURN_IF_ERROR(primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { return ConvertIfDestTypeMatches<primitive_type_constant>(literal, result); }, literal.shape().element_type())); return result; } absl::StatusOr<Literal> LiteralBase::Convert( PrimitiveType primitive_dest_type) const { return ConvertSwitch(*this, primitive_dest_type); } absl::StatusOr<Literal> LiteralBase::BitcastConvert( const Shape& dest_shape) const { if (ShapeUtil::ByteSizeOf(dest_shape) != ShapeUtil::ByteSizeOf(shape())) { return InvalidArgument( "Can not bitcast-convert from shape %s to a shape of different size %s", shape().ToString(), dest_shape.ToString()); } if (dest_shape.IsTuple() || shape().IsTuple()) { return InvalidArgument( "bitcast-convert is not valid for tuple shapes %s->%s", shape().ToString(), dest_shape.ToString()); } if (shape().is_dynamic() || dest_shape.is_dynamic()) { return InvalidArgument( "bitcast-convert is not valid for dynamic shape %s->%s", shape().ToString(), dest_shape.ToString()); } Literal out(dest_shape); std::memcpy(out.root_piece_.buffer(), root_piece().buffer(), root_piece().size_bytes_dense()); // Perform the reshape on little endian encoding even on big endian machines. if constexpr (!kLittleEndian) { // Swap byte ordering as per the input data type. size_t input_elem_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); TF_RETURN_IF_ERROR(tsl::ByteSwapArray( const_cast<char*>(out.root_piece().buffer()), input_elem_size, out.root_piece().size_bytes_dense() / input_elem_size)); // Swap byte ordering as per the output data type. size_t output_elem_size = ShapeUtil::ByteSizeOfPrimitiveType(dest_shape.element_type()); TF_RETURN_IF_ERROR(tsl::ByteSwapArray( const_cast<char*>(out.root_piece().buffer()), output_elem_size, out.root_piece().size_bytes_dense() / output_elem_size)); } return out; } absl::StatusOr<Literal> LiteralBase::ConvertToShape( const Shape& dest_shape) const { if (!dest_shape.IsTuple()) { return Convert(dest_shape.element_type()); } std::vector<Literal> elements; const auto tuple_element_count = ShapeUtil::TupleElementCount(shape()); elements.reserve(tuple_element_count); for (int i = 0; i < tuple_element_count; ++i) { auto element = LiteralSlice(*this, {i}); TF_ASSIGN_OR_RETURN( auto new_element, element.ConvertToShape(ShapeUtil::GetSubshape(dest_shape, {i}))); elements.push_back(std::move(new_element)); } return MutableLiteralBase::MoveIntoTuple(absl::MakeSpan(elements)); } /* static */ Literal MutableLiteralBase::MoveIntoTuple( absl::Span<Literal> elements) { std::vector<const Shape*> element_shapes; element_shapes.reserve(elements.size()); for (const Literal& element : elements) { element_shapes.push_back(&element.shape()); } Literal literal(ShapeUtil::MakeTupleShapeWithPtrs(element_shapes), /*allocate_arrays=*/false); for (int i = 0, end = elements.size(); i < end; ++i) { TF_CHECK_OK( literal.MoveFrom(std::move(elements[i]), /*dest_shape_index=*/{i})); } return literal; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualDynamicSize( const LiteralBase::Piece& other) const { DCHECK(ShapeUtil::Compatible(subshape(), other.subshape())); if (subshape().is_static()) { return true; } for (int64_t i = 0; i < subshape().rank(); ++i) { if (GetDynamicSize(i) != other.GetDynamicSize(i)) { return false; } } return true; } bool LiteralBase::Piece::EqualElements(const LiteralBase::Piece& other) const { if (subshape().is_static() && ShapeUtil::Equal(subshape(), other.subshape()) && subshape().IsArray()) { CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(size_bytes_dense(), other.size_bytes_dense()); if (primitive_util::IsSubByteNonPredType(subshape().element_type())) { CHECK(!primitive_util::IsFloatingPointType(subshape().element_type())); auto one_array = buffer(); auto two_array = other.buffer(); const int bits_per_element = primitive_util::BitWidth(subshape().element_type()); const uint8_t mask = LsbMask<uint8_t>(bits_per_element); for (int64_t i = 0; i < size_bytes_dense(); ++i) { if ((one_array[i] & mask) != (two_array[i] & mask)) return false; } return true; } return memcmp(buffer(), other.buffer(), size_bytes_dense()) == 0; } std::vector<int64_t> multi_index; return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeSrcT = NativeTypeOf<primitive_type_constant>; return EqualElementsInternal<NativeSrcT>(other, &multi_index); }, subshape().element_type()); } bool LiteralBase::Equal(const LiteralBase& other, bool layout_sensitive) const { // Checking the structure of tuple literals. Checks for dense arrays are // performed below. if (!ShapeUtil::EqualStructure(shape(), other.shape())) { return false; } return root_piece().ForEachSubpieceWithBool([&](const ShapeIndex& index, const Piece& piece) { const Piece& other_piece = other.piece(index); const Shape& subshape = piece.subshape(); const Shape& other_subshape = other_piece.subshape(); if (subshape.element_type() != other_subshape.element_type()) { return false; } if (!piece.subshape().IsArray()) { return true; } if (subshape.rank() != other_subshape.rank()) { return false; } if (layout_sensitive && (subshape.layout() != other_subshape.layout())) { return false; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (piece.GetDynamicSize(i) != other_piece.GetDynamicSize(i)) { return false; } } if (!piece.EqualElements(other_piece)) { return false; } return true; }); } return root_piece().ForEachSubpieceWithBool([&](const ShapeIndex& index, const Piece& piece) { const Piece& other_piece = other.piece(index); const Shape& subshape = piece.subshape(); const Shape& other_subshape = other_piece.subshape(); if (subshape.element_type() != other_subshape.element_type()) { return false; } if (!piece.subshape().IsArray()) { return true; } if (subshape.rank() != other_subshape.rank()) { return false; } if (layout_sensitive && (subshape.layout() != other_subshape.layout())) { return false; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (piece.GetDynamicSize(i) != other_piece.GetDynamicSize(i)) { return false; } } if (!piece.EqualElements(other_piece)) { return false; } return true; }); static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(std::complex<T> a, std::complex<T> b) { return EqualIncludingNan(a.real(), b.real()) && EqualIncludingNan(a.imag(), b.imag()); } static bool EqualIncludingNan(std::complex<T> a, std::complex<T> b) { return EqualIncludingNan(a.real(), b.real()) && EqualIncludingNan(a.imag(), b.imag()); } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } bool Literal::Piece::IsAll(const Literal& scalar) const { CHECK(ShapeUtil::IsScalar(scalar.shape())) << scalar.shape().ToString(); if (!subshape().IsArray()) { return false; } CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(subshape().element_type(), scalar.shape().element_type()); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, subshape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, int64_t Literal::Piece::CountAll(const Literal& scalar) const { CHECK(ShapeUtil::IsScalar(scalar.shape())) << scalar.shape().ToString(); if (!subshape().IsArray()) { return 0; } CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(subshape().element_type(), scalar.shape().element_type()); return primitive_util::ArrayTypeSwitch<int64_t>( [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, subshape().element_type()); } [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { bool LiteralBase::IsAll(const Literal& scalar) const { return root_piece().IsAll(scalar); } bool LiteralBase::IsAll(int8_t value) const { if (!shape().IsArray()) { return false; } PrimitiveType ty = shape().element_type(); if (primitive_util::IsFloatingPointType(ty)) { return IsAllFloatImpl(value, /*round_value=*/false); } if (primitive_util::IsUnsignedIntegralType(ty) && value < 0) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllFloat(float value) const { return IsAllFloatImpl(value, /*round_value=*/true); } bool LiteralBase::IsAllFloatImpl(float value, bool round_value) const { PrimitiveType ty = shape().element_type(); if (!primitive_util::IsFloatingPointType(ty)) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::FloatingPointTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllComplex(complex64 value) const { PrimitiveType ty = shape().element_type(); if (!primitive_util::IsComplexType(ty)) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::ComplexTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllFirst() const { if (!shape().IsArray()) { return false; } // Empty shapes are not all the first element since there is no first element. if (ShapeUtil::IsZeroElementArray(shape())) { return false; } absl::InlinedVector<int64_t, 4> start_indices(/*n=*/shape().rank(), 0); absl::InlinedVector<int64_t, 4> end_indices(/*n=*/shape().rank(), 1); Literal first = Slice(start_indices, end_indices); return IsAll(first.Reshape({}).value()); } bool LiteralBase::IsR1Iota() const { if (!shape().IsArray()) { return false; } CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); if (shape().rank() != 1) { return false; } return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, shape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, std::optional<int64_t> LiteralBase::IsR1StridedIota() const { if (!shape().IsArray() || shape().rank() != 1) { return std::nullopt; } CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); const int64_t elements = ShapeUtil::ElementsIn(shape()); const PrimitiveType type = shape().element_type(); if (elements <= 1 || !primitive_util::IsIntegralType(type)) { return std::nullopt; } return primitive_util::IntegralTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, bool LiteralBase::IsZero(absl::Span<const int64_t> indices) const { CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, shape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void LiteralBase::Piece::set_array_value_state(ArrayValueState state) { array_value_state_ = state; } LiteralBase::ArrayValueState LiteralBase::Piece::get_array_value_state() const { return array_value_state_; } void LiteralBase::Piece::WriteToProto(LiteralProto* proto) const { *proto->mutable_shape() = subshape().ToProto(); switch (subshape().element_type()) { case PRED: CopyToRepeatedField(proto->mutable_preds(), data<bool>()); break; case U2: *proto->mutable_u2s() = std::string( reinterpret_cast<const char*>(data<u2>().data()), size_bytes_dense()); break; case U4: *proto->mutable_u4s() = std::string( reinterpret_cast<const char*>(data<u4>().data()), size_bytes_dense()); break; case U8: proto->set_u8s(static_cast<const unsigned char*>(data<uint8_t>().data()), element_count()); break; case U16: *proto->mutable_u16s() = std::string(reinterpret_cast<const char*>(data<uint16_t>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_u16s()); } break; case U32: CopyToRepeatedField(proto->mutable_u32s(), data<uint32_t>()); break; case U64: CopyToRepeatedField(proto->mutable_u64s(), data<uint64_t>()); break; case S2: *proto->mutable_s2s() = std::string( reinterpret_cast<const char*>(data<s2>().data()), size_bytes_dense()); break; case S4: *proto->mutable_s4s() = std::string( reinterpret_cast<const char*>(data<s4>().data()), size_bytes_dense()); break; case S8: proto->set_s8s(static_cast<const signed char*>(data<int8_t>().data()), element_count()); break; case S16: *proto->mutable_s16s() = std::string(reinterpret_cast<const char*>(data<int16_t>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_s16s()); } break; case S32: CopyToRepeatedField(proto->mutable_s32s(), data<int32_t>()); break; case S64: CopyToRepeatedField(proto->mutable_s64s(), data<int64_t>()); break; case F8E5M2: *proto->mutable_f8e5m2s() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e5m2>().data()), size_bytes_dense()); break; case F8E4M3FN: *proto->mutable_f8e4m3fns() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3fn>().data()), size_bytes_dense()); break; case F8E4M3B11FNUZ: *proto->mutable_f8e4m3b11fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3b11fnuz>().data()), size_bytes_dense()); break; case F8E5M2FNUZ: *proto->mutable_f8e5m2fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e5m2fnuz>().data()), size_bytes_dense()); break; case F8E4M3FNUZ: *proto->mutable_f8e4m3fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3fnuz>().data()), size_bytes_dense()); break; case F16: *proto->mutable_f16s() = std::string(reinterpret_cast<const char*>(data<half>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_f16s()); } break; case BF16: *proto->mutable_bf16s() = std::string(reinterpret_cast<const char*>(data<bfloat16>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_bf16s()); } break; case F32: CopyToRepeatedField(proto->mutable_f32s(), data<float>()); break; case F64: CopyToRepeatedField(proto->mutable_f64s(), data<double>()); break; case C64: for (complex64 value : data<complex64>()) { proto->add_c64s(value.real()); proto->add_c64s(value.imag()); } break; case C128: for (complex128 value : data<complex128>()) { proto->add_c128s(value.real()); proto->add_c128s(value.imag()); } break; case TUPLE: case TOKEN: // Nothing to do but assign the shape which is done above. return; default: // TODO(b/111551621): Support serializing more PrimitiveTypes. LOG(FATAL) << "Unhandled primitive type " << PrimitiveType_Name(subshape().element_type()); } } const void* LiteralBase::Piece::untyped_data() const { DCHECK(LayoutUtil::IsDenseArray(subshape())) << ShapeUtil::HumanString(subshape()); return buffer(); } void* LiteralBase::Piece::untyped_data() { DCHECK(LayoutUtil::IsDenseArray(subshape())) << ShapeUtil::HumanString(subshape()); return buffer(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status LiteralBase::Piece::CopyFromProto(const LiteralProto& proto) { // These conditions should have been checked in // MutableLiteralBase::CreateFromProto. TF_RET_CHECK(proto.has_shape()); Shape shape(proto.shape()); TF_RET_CHECK(LayoutUtil::HasLayout(shape)); TF_RET_CHECK(ShapeUtil::Equal(shape, subshape())); switch (subshape().element_type()) { case PRED: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<bool>(), proto.preds())); break; case S2: { const std::string& s(proto.s2s()); TF_RET_CHECK(data<s2>().size() * sizeof(s2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case S4: { const std::string& s(proto.s4s()); TF_RET_CHECK(data<s4>().size() * sizeof(s4) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case S8: { auto s8_data = data<int8_t>(); TF_RET_CHECK(proto.s8s().size() == s8_data.size()); std::copy(proto.s8s().begin(), proto.s8s().end(), s8_data.begin()); break; } case S16: { const std::string& s(proto.s16s()); TF_RET_CHECK(data<int16_t>().size() * sizeof(int16_t) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case S32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<int32_t>(), proto.s32s())); break; case S64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<int64_t>(), proto.s64s())); break; case U2: { const std::string& s(proto.u2s()); TF_RET_CHECK(data<u2>().size() * sizeof(u2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case U4: { const std::string& s(proto.u4s()); TF_RET_CHECK(data<u4>().size() * sizeof(u4) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case U8: { auto u8_data = data<uint8_t>(); TF_RET_CHECK(proto.u8s().size() == u8_data.size()); std::copy(proto.u8s().begin(), proto.u8s().end(), u8_data.begin()); break; } case U16: { const std::string& s(proto.u16s()); TF_RET_CHECK(data<uint16_t>().size() * sizeof(uint16_t) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case U32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<uint32_t>(), proto.u32s())); break; case U64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<uint64_t>(), proto.u64s())); break; case F8E5M2: { const std::string& s(proto.f8e5m2s()); TF_RET_CHECK(data<tsl::float8_e5m2>().size() * sizeof(tsl::float8_e5m2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3FN: { const std::string& s(proto.f8e4m3fns()); TF_RET_CHECK(data<tsl::float8_e4m3fn>().size() * sizeof(tsl::float8_e4m3fn) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3B11FNUZ: { const std::string& s(proto.f8e4m3b11fnuzs()); TF_RET_CHECK(data<tsl::float8_e4m3b11fnuz>().size() * sizeof(tsl::float8_e4m3b11fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E5M2FNUZ: { const std::string& s(proto.f8e5m2fnuzs()); TF_RET_CHECK(data<tsl::float8_e5m2fnuz>().size() * sizeof(tsl::float8_e5m2fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3FNUZ: { const std::string& s(proto.f8e4m3fnuzs()); TF_RET_CHECK(data<tsl::float8_e4m3fnuz>().size() * sizeof(tsl::float8_e4m3fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F16: { const std::string& s(proto.f16s()); TF_RET_CHECK(data<half>().size() * sizeof(half) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case BF16: { const std::string& s(proto.bf16s()); TF_RET_CHECK(data<bfloat16>().size() * sizeof(bfloat16) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case F32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<float>(), proto.f32s())); break; case F64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<double>(), proto.f64s())); break; case C64: { auto complex_data = data<complex64>(); TF_RET_CHECK(proto.c64s_size() == complex_data.size() * 2); for (int64_t i = 0; i < complex_data.size(); ++i) { complex_data[i] = complex64{proto.c64s(i * 2), proto.c64s(i * 2 + 1)}; } break; } case C128: { auto complex_data = data<complex128>(); const int64_t complex_data_size_doubled = complex_data.size() * 2; TF_RET_CHECK(proto.c128s_size() == complex_data_size_doubled); for (int64_t i = 0, end = complex_data.size(); i < end; ++i) { complex_data[i] = complex128{proto.c128s(i * 2), proto.c128s(i * 2 + 1)}; } break; } case TUPLE: return InvalidArgument("Should not be called on tuple shapes: %s", ShapeUtil::HumanString(subshape())); default: return InvalidArgument("Is called on unsupported shape: %s", ShapeUtil::HumanString(subshape())); } return absl::OkStatus(); } bool LiteralBase::Piece::IsKnown() const { if (array_value_state_ != ArrayValueState::kKnown) { return false; } if (subshape().IsTuple()) { bool are_all_leaf_arrays_known = true; ForEachSubpiece([&are_all_leaf_arrays_known](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_known &= piece.IsKnown(); }); return are_all_leaf_arrays_known; } return true; } ForEachSubpiece([&are_all_leaf_arrays_known](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_known &= piece.IsKnown(); }); bool LiteralBase::Piece::IsDetermined() const { if (array_value_state_ == ArrayValueState::kUndetermined) { return false; } if (subshape().IsTuple()) { bool are_all_leaf_arrays_determined = true; ForEachSubpiece([&are_all_leaf_arrays_determined](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_determined &= piece.IsDetermined(); }); return are_all_leaf_arrays_determined; } return true; } ForEachSubpiece([&are_all_leaf_arrays_determined](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_determined &= piece.IsDetermined(); }); LiteralProto LiteralBase::ToProto() const { LiteralProto proto; root_piece().ForEachSubpiece( [&](const ShapeIndex& index, const Piece& piece) { LiteralProto* proto_piece = &proto; for (int64_t i : index) { while (proto_piece->tuple_literals_size() <= i) { proto_piece->add_tuple_literals(); } proto_piece = proto_piece->mutable_tuple_literals(i); } piece.WriteToProto(proto_piece); }); return proto; } [&](const ShapeIndex& index, const Piece& piece) { LiteralProto* proto_piece = &proto; for (int64_t i : index) { while (proto_piece->tuple_literals_size() <= i) { proto_piece->add_tuple_literals(); } proto_piece = proto_piece->mutable_tuple_literals(i); } piece.WriteToProto(proto_piece); }); const void* LiteralBase::untyped_data(const ShapeIndex& shape_index) const { return piece(shape_index).untyped_data(); } void* MutableLiteralBase::untyped_data(const ShapeIndex& shape_index) { return piece(shape_index).untyped_data(); } int64_t LiteralBase::size_bytes(const ShapeIndex& shape_index) const { return piece(shape_index).size_bytes_dense(); } std::string LiteralBase::GetR1U8AsString() const { CHECK(shape().IsArray()); CHECK_EQ(shape().rank(), 1); CHECK_EQ(shape().element_type(), U8); return std::string(absl::bit_cast<const char*>(data<uint8_t>().data()), ShapeUtil::ElementsIn(shape())); } void MutableBorrowingLiteral::CopyPieceSubtree(const Shape& shape, const Piece* src_piece, Piece* dest_piece) { DCHECK(ShapeUtil::Equal(src_piece->subshape(), dest_piece->subshape())) << "src_piece has shape: " << ShapeUtil::HumanString(src_piece->subshape()) << "dest_piece has shape: " << ShapeUtil::HumanString(dest_piece->subshape()); dest_piece->set_array_value_state(src_piece->get_array_value_state()); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); Piece child_piece; child_piece.set_subshape(&subshape); CopyPieceSubtree(subshape, &src_piece->child(i), &child_piece); dest_piece->emplace_back(std::move(child_piece)); } } else if (shape.IsArray()) { dest_piece->set_buffer(const_cast<char*>(src_piece->buffer())); } } MutableLiteralBase::~MutableLiteralBase() = default; MutableBorrowingLiteral::MutableBorrowingLiteral( const MutableBorrowingLiteral& literal) : MutableLiteralBase() { shape_ = literal.shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.root_piece(), root_piece_); } MutableBorrowingLiteral& MutableBorrowingLiteral::operator=( const MutableBorrowingLiteral& literal) { shape_ = literal.shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.root_piece(), root_piece_); return *this; } MutableBorrowingLiteral::MutableBorrowingLiteral(MutableLiteralBase* literal) : MutableLiteralBase() { shape_ = literal->shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal->root_piece(), root_piece_); } MutableBorrowingLiteral::MutableBorrowingLiteral( MutableBorrowingLiteral literal, const ShapeIndex& view_root) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(literal.piece(view_root).subshape()); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.piece(view_root), root_piece_); } MutableBorrowingLiteral::MutableBorrowingLiteral(const char* src_buf_ptr, const Shape& shape) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(shape); CHECK(LayoutUtil::HasLayout(*shape_)); CHECK(!shape_->IsTuple()); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); root_piece_->set_buffer(const_cast<char*>(src_buf_ptr)); } MutableBorrowingLiteral::MutableBorrowingLiteral(absl::Span<char*> src_buf_ptrs, const Shape& shape) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(shape); if (!shape_->IsTuple()) { CHECK_EQ(src_buf_ptrs.size(), 1); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); root_piece_->set_buffer(const_cast<char*>(src_buf_ptrs[0])); } else { CHECK(!ShapeUtil::IsNestedTuple(*shape_)); CHECK_EQ(src_buf_ptrs.size(), ShapeUtil::TupleElementCount(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); for (int i = 0; i < src_buf_ptrs.size(); ++i) { Piece child_piece; const auto& src_shape = shape_->tuple_shapes(i); CHECK(src_shape.IsArray()); child_piece.set_subshape(&src_shape); child_piece.set_buffer(src_buf_ptrs[i]); root_piece_->emplace_back(std::move(child_piece)); } } } MutableBorrowingLiteral::MutableBorrowingLiteral(ShapeTree<char*> src_buf_ptrs) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(src_buf_ptrs.shape()); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); BuildPieceSubtree(*shape_, root_piece_); root_piece_->ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); } [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); MutableBorrowingLiteral::~MutableBorrowingLiteral() { if (root_piece_ != nullptr) { delete root_piece_; } } LiteralSlice::LiteralSlice(const LiteralBase& literal) : LiteralBase(), root_piece_(&literal.root_piece()) {} LiteralSlice::LiteralSlice(const LiteralBase& literal, const ShapeIndex& view_root) : LiteralBase(), root_piece_(&literal.piece(view_root)) {} BorrowingLiteral::BorrowingLiteral(const char* src_buf_ptr, const Shape& shape) : LiteralBase(), shape_(std::make_unique<Shape>(shape)) { CHECK(shape_->IsArray()); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); root_piece_.set_buffer(const_cast<char*>(src_buf_ptr)); } BorrowingLiteral::BorrowingLiteral(absl::Span<const char* const> src_buf_ptrs, const Shape& shape) : LiteralBase(), shape_(std::make_unique<Shape>(shape)) { CHECK(shape_->IsTuple()); CHECK(!ShapeUtil::IsNestedTuple(*shape_)); CHECK_EQ(src_buf_ptrs.size(), ShapeUtil::TupleElementCount(*shape_)); root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); BuildPieceSubtree(*shape_, &root_piece_); for (int i = 0, end = src_buf_ptrs.size(); i < end; ++i) { const auto& src_shape = shape_->tuple_shapes(i); CHECK(src_shape.IsArray()); root_piece_.child(i).set_buffer(const_cast<char*>(src_buf_ptrs[i])); } } BorrowingLiteral::BorrowingLiteral(ShapeTree<const char*> src_buf_ptrs) : LiteralBase(), shape_(std::make_unique<Shape>(src_buf_ptrs.shape())) { root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); BuildPieceSubtree(*shape_, &root_piece_); root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); } [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); });
#include "xla/literal.h" #include <algorithm> #include <cmath> #include <complex> #include <cstdint> #include <functional> #include <limits> #include <random> #include <string> #include <tuple> #include <utility> #include <vector> #include "absl/base/casts.h" #include "absl/hash/hash.h" #include "absl/random/random.h" #include "absl/status/status.h" #include "absl/strings/match.h" #include "absl/types/span.h" #include "xla/array.h" #include "xla/array2d.h" #include "xla/array3d.h" #include "xla/array4d.h" #include "xla/index_util.h" #include "xla/layout.h" #include "xla/layout_util.h" #include "xla/literal_util.h" #include "xla/primitive_util.h" #include "xla/shape.h" #include "xla/shape_tree.h" #include "xla/shape_util.h" #include "xla/test.h" #include "xla/types.h" #include "xla/util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/errors.h" #include "tsl/platform/logging.h" // IWYU pragma: keep #include "tsl/platform/macros.h" #include "tsl/platform/ml_dtypes.h" #include "tsl/platform/statusor.h" #include "tsl/platform/test_benchmark.h" class LiteralUtilTest : public ::testing::Test { protected: LiteralUtilTest() { Array4D<float> arr4d({ // clang-format off { // i0=0 { // i1=0 {1, 2, 3}, // i2=0 {4, 5, 6}, // i2=1 {7, 8, 9}, // i2=2 }, { // i1=1 {11, 12, 13}, {14, 15, 16}, {17, 18, 19}, }, }, { // i0=1 { // i1=0 {101, 102, 103}, {104, 105, 106}, {107, 108, 109}, }, { // i1=1 {201, 202, 203}, // i2=0 {204, 205, 206}, // i2=1 {207, 208, 209}, // i2=2 }, }, // clang-format on }); layout_r2_dim0major_ = LayoutUtil::MakeLayout({1, 0}); layout_r2_dim0minor_ = LayoutUtil::MakeLayout({0, 1}); layout_r3_dim0major_ = LayoutUtil::MakeLayout({2, 1, 0}); layout_r3_dim0minor_ = LayoutUtil::MakeLayout({0, 1, 2}); layout_r4_dim0major_ = LayoutUtil::MakeLayout({3, 2, 1, 0}); layout_r4_dim0minor_ = LayoutUtil::MakeLayout({0, 1, 2, 3}); literal_r4_2x2x3x3_dim0major_ = LiteralUtil::CreateR4FromArray4DWithLayout<float>(arr4d, layout_r4_dim0major_); literal_r4_2x2x3x3_dim0minor_ = LiteralUtil::CreateR4FromArray4DWithLayout<float>(arr4d, layout_r4_dim0minor_); } Layout layout_r2_dim0major_; Layout layout_r2_dim0minor_; Layout layout_r3_dim0major_; Layout layout_r3_dim0minor_; Layout layout_r4_dim0major_; Layout layout_r4_dim0minor_; Literal literal_r4_2x2x3x3_dim0major_; Literal literal_r4_2x2x3x3_dim0minor_; }; TEST_F(LiteralUtilTest, C128Equality) { // Test equality with tuples. auto vector = LiteralUtil::CreateR1<complex128>({{1.0, 2.0}, {3.0, 4.0}}); // Tuple with the same elements. One element is shared with the original // tuple, the other is a clone of the element in the original tuple. auto vector_clone = LiteralUtil::CreateR1<complex128>({{1.0, 2.0}, {3.0, 4.0}}); EXPECT_EQ(vector, vector_clone); auto vector_reversed = LiteralUtil::CreateR1<complex128>({{3.0, 4.0}, {1.0, 2.0}}); EXPECT_NE(vector, vector_reversed); }
LiteralUtilTest_C64Equality
xla/literal_test.cc
bool LiteralProtoHasValues(const LiteralProto& proto) { return !proto.s2s().empty() || !proto.s4s().empty() || !proto.s8s().empty() || !proto.s16s().empty() || proto.s32s_size() || proto.s64s_size() || !proto.u2s().empty() || !proto.u4s().empty() || !proto.u8s().empty() || !proto.u16s().empty() || proto.u32s_size() || proto.u64s_size() || !proto.f8e5m2s().empty() || !proto.f8e4m3fns().empty() || !proto.f8e4m3b11fnuzs().empty() || !proto.f8e5m2fnuzs().empty() || !proto.f8e4m3fnuzs().empty() || !proto.f16s().empty() || !proto.bf16s().empty() || proto.f32s_size() || proto.f64s_size() || proto.c64s_size() || proto.c128s_size() || proto.preds_size() || proto.tuple_literals_size(); } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { const Shape& NilShape() { static const Shape* shape = new Shape(TUPLE, {}, {}, {}); return *shape; } const Shape* TryInternShape(const Shape& shape) { if (shape.IsTuple() && shape.tuple_shapes_size() == 0) { return &NilShape(); } if (shape.IsArray() && shape.dimensions_size() == 0 && shape.is_static() && shape.layout().tiles_size() == 0 && shape.layout().memory_space() == 0) { return &ScalarShape(shape.element_type()); } return nullptr; } StrideConfig::StrideConfig(const Shape& source_shape, const Shape& dest_shape, absl::Span<const int64_t> dimensions) : dimensions(dimensions), base(dimensions.size(), 0), step(dimensions.size(), 1) { if (!dimensions.empty()) { // Selects the shape with the largest minor dimension as the one upon // which to run the tight stride loop. if (dimensions[LayoutUtil::Minor(source_shape.layout(), 0)] >= dimensions[LayoutUtil::Minor(dest_shape.layout(), 0)]) { minor_dimension = LayoutUtil::Minor(source_shape.layout(), 0); dest_stride = IndexUtil::GetDimensionStride(dest_shape, minor_dimension); } else { minor_dimension = LayoutUtil::Minor(dest_shape.layout(), 0); source_stride = IndexUtil::GetDimensionStride(source_shape, minor_dimension); } minor_loop_size = dimensions[minor_dimension]; step[minor_dimension] = minor_loop_size; } } LiteralBase::~LiteralBase() = default; const Shape& LiteralBase::shape() const { return root_piece().subshape(); } const char* LiteralBase::Piece::buffer() const { // std::visit is avoided here due to its code size issues. if (auto* r = std::get_if<DenseRep>(&rep_)) { return r->data; } if (auto* r = std::get_if<DenseInlinedRep>(&rep_)) { return r->data; } DCHECK(std::holds_alternative<TupleRep>(rep_) || std::holds_alternative<Uninitialized>(rep_)); return nullptr; } const LiteralBase::Piece& LiteralBase::piece( const ShapeIndex& shape_index) const { const Piece* piece = &root_piece(); for (const auto i : shape_index) { DCHECK_GE(i, 0); DCHECK_LT(i, piece->children_size()); piece = &piece->child(i); } return *piece; } std::ostream& operator<<(std::ostream& out, const Literal& literal) { out << literal.ToString(); return out; } Shape* MutableLiteralBase::mutable_shape_do_not_use() { const Shape* const_shape = shape_.get(); if (!shape_.OwnsPtr()) { shape_ = MaybeOwningShapePtr(std::make_unique<Shape>(*shape_)); } Shape* shape = shape_.get_mutable(); if (shape != const_shape) { std::function<void(const Shape&, Piece*)> set_piece_shapes = [&set_piece_shapes](const Shape& shape, Piece* piece) { piece->set_subshape(&shape); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); set_piece_shapes(subshape, &piece->child(i)); } } }; set_piece_shapes(*shape, &mutable_root_piece()); } return shape; } [&set_piece_shapes](const Shape& shape, Piece* piece) { piece->set_subshape(&shape); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); set_piece_shapes(subshape, &piece->child(i)); } } }; Literal::Literal() : Literal(NilShape()) {} Literal::Literal(const Shape& shape) : Literal(shape, /*allocate_arrays=*/true) {} void Literal::SetShape(const Shape& shape) { Shape shape_storage; const Shape* shape_ptr = &shape; if (LayoutUtil::HasCustomElementSizeInBits(shape)) { shape_storage = shape; shape_storage.mutable_layout()->set_element_size_in_bits(0); shape_ptr = &shape_storage; } if (const Shape* intered_shape_ptr = TryInternShape(*shape_ptr)) { shape_ = intered_shape_ptr; } else { shape_ = std::make_unique<Shape>(*shape_ptr); } } void Literal::SetPiece(const Shape& shape, Piece* piece, bool allocate_arrays, ArrayValueState leaf_array_value_state) { if (shape.IsTuple()) { for (const Shape& subshape : shape.tuple_shapes()) { Piece child_piece; child_piece.set_subshape(&subshape); SetPiece(subshape, &child_piece, allocate_arrays, leaf_array_value_state); piece->emplace_back(std::move(child_piece)); } } else if (shape.IsArray()) { DCHECK(LayoutUtil::IsDenseArray(shape)) << "literal array storage is currently only supported for dense " "arrays: " << shape; piece->set_array_value_state(leaf_array_value_state); if (leaf_array_value_state == LiteralBase::ArrayValueState::kKnown && allocate_arrays) { piece->AllocateBuffers(); } } } Literal::Literal(const Shape& shape, bool allocate_arrays, ArrayValueState leaf_array_value_state) : MutableLiteralBase() { SetShape(shape); CHECK(leaf_array_value_state != ArrayValueState::kKnown || LayoutUtil::HasLayout(*shape_)); root_piece_.set_subshape(shape_.get()); CHECK(&root_piece_.subshape() == shape_.get()); SetPiece(*shape_, &root_piece_, allocate_arrays, leaf_array_value_state); } Literal::~Literal() { DeallocateBuffers(); } void Literal::DeallocateBuffers() { root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { piece->DeallocateBuffers(); }); } Literal::Literal(Literal&& other) : MutableLiteralBase() { *this = std::move(other); } Literal& Literal::operator=(Literal&& other) { DCHECK(&other.root_piece_.subshape() == other.shape_.get()); using std::swap; swap(shape_, other.shape_); swap(root_piece_, other.root_piece_); DCHECK(&root_piece_.subshape() == shape_.get()); return *this; } Literal LiteralBase::CreateFromShape(const Shape& shape) { Literal literal(shape); literal.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (piece->subshape().IsArray()) { memset(piece->untyped_data(), 0, piece->size_bytes_dense()); } }); return literal; } [&](const ShapeIndex& index, Piece* piece) { if (piece->subshape().IsArray()) { memset(piece->untyped_data(), 0, piece->size_bytes_dense()); } }); Literal LiteralBase::CreateFromShapeWithUnknownLeafArrays(const Shape& shape) { Literal literal(shape, /*allocate_arrays=*/false, ArrayValueState::kUnknown); return literal; } Literal LiteralBase::CreateFromShapeWithUndeterminedLeafArrays( const Shape& shape) { Literal literal(shape, /*allocate_arrays=*/false, ArrayValueState::kUndetermined); return literal; } int32_t LiteralBase::GetDynamicSize(int64_t dim_index) const { return GetDynamicSize(dim_index, {}); } int32_t LiteralBase::GetDynamicSize(int64_t dim_index, const ShapeIndex& shape_index) const { return piece(shape_index).GetDynamicSize(dim_index); } std::optional<int64_t> LiteralBase::GetFirstInteger() const { if (!primitive_util::IsIntegralType(shape().element_type())) { return std::nullopt; } return primitive_util::IntegralTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, void LiteralBase::BuildPieceSubtree(const Shape& shape, Piece* piece) { CHECK(shape.IsTuple()); for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); Piece child_piece; child_piece.set_subshape(&subshape); if (subshape.IsTuple()) { BuildPieceSubtree(subshape, &child_piece); } piece->emplace_back(std::move(child_piece)); } } absl::Status LiteralBase::SerializeToString(std::string* output) const { ShapeProto shape_proto = shape().ToProto(); TF_ASSIGN_OR_RETURN(int64_t size, ShapeUtil::SerializedSizeWithProto(shape(), shape_proto)); output->resize(size); return SerializeWithShapeProto(shape_proto, output->data()); } absl::StatusOr<std::string> LiteralBase::SerializeAsString() const { std::string result; TF_RETURN_IF_ERROR(SerializeToString(&result)); return std::move(result); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { void MutableLiteralBase::CopyElementFrom(const LiteralSlice& src_literal, absl::Span<const int64_t> src_index, absl::Span<const int64_t> dest_index) { DCHECK(LayoutUtil::IsDenseArray(shape())); DCHECK_EQ(shape().element_type(), src_literal.shape().element_type()); const int64_t src_linear_index = IndexUtil::MultidimensionalIndexToLinearIndex(src_literal.shape(), src_index); const int64_t dest_linear_index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), dest_index); const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); char* dest_address = static_cast<char*>(untyped_data()) + dest_linear_index * primitive_size; const char* source_address = static_cast<const char*>(src_literal.untyped_data()) + src_linear_index * primitive_size; if (dest_address != source_address) { memcpy(dest_address, source_address, primitive_size); } } /* static */ absl::StatusOr<Literal> MutableLiteralBase::CreateFromProto( const LiteralProto& proto, bool prohibit_empty_literal) { if (!proto.has_shape()) { return InvalidArgument("LiteralProto has no shape"); } Shape shape(proto.shape()); if (ShapeUtil::HasPrimitiveType(shape, OPAQUE_TYPE)) { return InvalidArgument( "Literal shape cannot include OPAQUE_TYPE sub-shape"); } if (!LayoutUtil::HasLayout(shape)) { return InvalidArgument("LiteralProto has no layout"); } if (LayoutUtil::IsSparseArray(shape)) { return Unimplemented("Sparse literals are not supported"); } TF_RETURN_IF_ERROR(ShapeUtil::ValidateShapeWithOptionalLayout(shape)); Literal literal(shape); TF_RETURN_IF_ERROR(literal.root_piece_.ForEachMutableSubpieceWithStatus( [&](const ShapeIndex& index, Piece* piece) -> absl::Status { const LiteralProto* proto_element = &proto; for (int64_t i : index) { CHECK(i < proto_element->tuple_literals_size()); proto_element = &proto_element->tuple_literals(i); } if (piece->subshape().IsTuple()) { if (proto_element->tuple_literals_size() != ShapeUtil::TupleElementCount(piece->subshape())) { return InvalidArgument( "Expected %d tuple elements in LiteralProto, has %d", ShapeUtil::TupleElementCount(piece->subshape()), proto_element->tuple_literals_size()); } return absl::OkStatus(); } if (piece->subshape().element_type() == TOKEN) { return absl::OkStatus(); } CHECK(piece->subshape().IsArray()); // When prohibit_empty_literal is false (allowing literal with no // values), only copy from proto if the literal proto has values. This // mode is used for a learned cost model. if (prohibit_empty_literal || LiteralProtoHasValues(*proto_element)) { TF_RETURN_IF_ERROR(piece->CopyFromProto(*proto_element)); } return absl::OkStatus(); })); return std::move(literal); } TF_RETURN_IF_ERROR(literal.root_piece_.ForEachMutableSubpieceWithStatus( Literal Literal::SubLiteral(ShapeIndexView shape_index) { if (!shape_index.empty()) { auto decomposed = this->DecomposeTuple(); return decomposed.at(shape_index.front()) .SubLiteral(shape_index.subspan(1)); } else { return std::move(*this); } } std::vector<Literal> Literal::DecomposeTuple() { CHECK(shape().IsTuple()); std::vector<Literal> elements; const auto tuple_element_count = ShapeUtil::TupleElementCount(shape()); elements.reserve(tuple_element_count); for (int i = 0; i < tuple_element_count; ++i) { elements.push_back(Literal(ShapeUtil::GetSubshape(shape(), {i}), /*allocate_arrays=*/false)); Literal& element = elements.back(); element.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* dest_piece) { if (dest_piece->subshape().IsTuple()) { return; } ShapeIndex src_index = {i}; for (int64_t j : index) { src_index.push_back(j); } Piece& src_piece = piece(src_index); // Move the respective buffer over to the element Literal. dest_piece->MoveDataFrom(src_piece); }); } // Set this literal to be nil-shaped. *this = Literal(); return elements; } [&](const ShapeIndex& index, Piece* dest_piece) { if (dest_piece->subshape().IsTuple()) { return; } ShapeIndex src_index = {i}; for (int64_t j : index) { src_index.push_back(j); } Piece& src_piece = piece(src_index); // Move the respective buffer over to the element Literal. dest_piece->MoveDataFrom(src_piece); }); void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } int32_t LiteralBase::Piece::GetDynamicSize(int64_t dim_index) const { CHECK(LayoutUtil::IsDenseArray(subshape())); if (!subshape_->is_dynamic_dimension(dim_index)) { // This is a static dimension, return size. return subshape_->dimensions(dim_index); } return dynamic_size_buffer()[dim_index]; } void LiteralBase::Piece::SetDynamicSize(int64_t dim_index, int32_t size) { CHECK(LayoutUtil::IsDenseArray(subshape())); CHECK(subshape_->is_dynamic_dimension(dim_index)); dynamic_size_buffer()[dim_index] = size; } void LiteralBase::Piece::AllocateBuffers() { const int64_t bytes = total_bytes_dense(); if (bytes > kMaxInlinedBytes) { CHECK_EQ(buffer(), nullptr); rep_.emplace<DenseRep>(); set_buffer( static_cast<char*>(tsl::port::AlignedMalloc(bytes, kMinimumAlignment))); } else { rep_.emplace<DenseInlinedRep>(); } } void LiteralBase::Piece::DeallocateBuffers() { if (auto* array_rep = GetDenseRep()) { tsl::port::AlignedFree(array_rep->data); rep_.emplace<Uninitialized>(); } } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } absl::Status LiteralBase::Piece::CopyFrom(const LiteralBase::Piece& src, bool only_dynamic_bound) { CHECK(subshape_ != nullptr); CHECK(src.subshape_ != nullptr); CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK(LayoutUtil::IsDenseArray(src.subshape())) << __func__ << " is only supported for dense arrays: " << src.subshape(); if (!only_dynamic_bound) { CHECK(ShapeUtil::Compatible(subshape(), src.subshape())); } if (src.array_value_state_ == ArrayValueState::kUnknown || src.array_value_state_ == ArrayValueState::kUndetermined) { if (array_value_state_ == ArrayValueState::kKnown) { DeallocateBuffers(); } array_value_state_ = src.array_value_state_; return absl::OkStatus(); } else { CHECK(src.array_value_state_ == ArrayValueState::kKnown); if (array_value_state_ == ArrayValueState::kUndetermined || array_value_state_ == ArrayValueState::kUnknown) { AllocateBuffers(); } array_value_state_ = src.array_value_state_; } if (ShapeUtil::Equal(subshape(), src.subshape())) { // If the layouts are equal it's faster just to memcpy. memcpy(buffer(), src.buffer(), src.size_bytes_dense()); } else { std::vector<int64_t> origin(subshape().rank(), 0); primitive_util::ArrayTypeSwitch<void>( [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, subshape().element_type()); } DCHECK_EQ(dynamic_size_buffer_bytes(), src.dynamic_size_buffer_bytes()); if (subshape().is_dynamic() && src.subshape().is_dynamic()) { memcpy(dynamic_size_buffer(), src.dynamic_size_buffer(), src.dynamic_size_buffer_bytes()); } return absl::OkStatus(); } [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, void MutableLiteralBase::SetDynamicSize(int64_t dim_index, int32_t size) { return SetDynamicSize(dim_index, {}, size); } void MutableLiteralBase::SetDynamicSize(int64_t dim_index, const ShapeIndex& shape_index, int32_t size) { Shape* subshape = ShapeUtil::GetMutableSubshape(mutable_shape_do_not_use(), shape_index); CHECK(LayoutUtil::IsDenseArray(*subshape)) << __func__ << " is only supported for dense arrays: " << *subshape; CHECK_GE(subshape->dimensions(dim_index), size); subshape->set_dynamic_dimension(dim_index, true); CHECK_EQ(&piece(shape_index).subshape(), subshape); piece(shape_index).SetDynamicSize(dim_index, size); } absl::Status MutableLiteralBase::CopyFrom(const LiteralSlice& src_literal, const ShapeIndex& dest_shape_index, const ShapeIndex& src_shape_index, bool only_dynamic_bound) { const Shape& dest_subshape = ShapeUtil::GetSubshape(shape(), dest_shape_index); const Shape& src_subshape = ShapeUtil::GetSubshape(src_literal.shape(), src_shape_index); if (only_dynamic_bound) { auto& bound_shape = dest_subshape.is_static() ? src_subshape : dest_subshape; auto& compact_shape = dest_subshape.is_static() ? dest_subshape : src_subshape; CHECK(ShapeUtil::DynamicShapeIsCompatible(compact_shape, bound_shape)) << compact_shape.ToString() << " vs " << bound_shape.ToString(); } else { if (!ShapeUtil::Compatible(dest_subshape, src_subshape)) { return InvalidArgument( "Destination subshape incompatible with source subshape: %s vs %s", ShapeUtil::HumanString(dest_subshape), ShapeUtil::HumanString(src_subshape)); } } return mutable_root_piece().ForEachMutableSubpieceWithStatus( [&](const ShapeIndex& index, Piece* piece) { if (!piece->subshape().IsArray()) { return absl::OkStatus(); } // Determine if this index is in the part of this literal that we want // to copy over from src_literal. bool in_subtree_to_copy = true; for (int i = 0; i < dest_shape_index.size(); ++i) { if (index[i] != dest_shape_index[i]) { in_subtree_to_copy = false; break; } } if (!in_subtree_to_copy) { return absl::OkStatus(); } // Construct the index of the corresponding piece in the source literal. ShapeIndex src_piece_index = src_shape_index; for (int64_t i = dest_shape_index.size(), end = index.size(); i < end; ++i) { src_piece_index.push_back(index[i]); } TF_RETURN_IF_ERROR( piece->CopyFrom(src_literal.piece(src_piece_index), /*only_dynamic_bound=*/only_dynamic_bound)); return absl::OkStatus(); }); } [&](const ShapeIndex& index, Piece* piece) { if (!piece->subshape().IsArray()) { return absl::OkStatus(); } // Determine if this index is in the part of this literal that we want // to copy over from src_literal. bool in_subtree_to_copy = true; for (int i = 0; i < dest_shape_index.size(); ++i) { if (index[i] != dest_shape_index[i]) { in_subtree_to_copy = false; break; } } if (!in_subtree_to_copy) { return absl::OkStatus(); } // Construct the index of the corresponding piece in the source literal. ShapeIndex src_piece_index = src_shape_index; for (int64_t i = dest_shape_index.size(), end = index.size(); i < end; ++i) { src_piece_index.push_back(index[i]); } TF_RETURN_IF_ERROR( piece->CopyFrom(src_literal.piece(src_piece_index), /*only_dynamic_bound=*/only_dynamic_bound)); return absl::OkStatus(); }); absl::Status Literal::MoveFrom(Literal&& src_literal, const ShapeIndex& dest_shape_index) { const Shape& dest_subshape = ShapeUtil::GetSubshape(shape(), dest_shape_index); if (!ShapeUtil::Equal(dest_subshape, src_literal.shape())) { return InvalidArgument( "Destination subshape not equal to source shape: %s vs %s", ShapeUtil::HumanString(dest_subshape), ShapeUtil::HumanString(src_literal.shape())); } src_literal.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& src_index, Piece* src_piece) { if (!src_piece->subshape().IsArray()) { return; } ShapeIndex dest_index = dest_shape_index; for (int64_t i : src_index) { dest_index.push_back(i); } Piece& dest_piece = piece(dest_index); dest_piece.DeallocateBuffers(); dest_piece.MoveDataFrom(*src_piece); }); src_literal.shape_ = MaybeOwningShapePtr(&NilShape()); src_literal.root_piece_ = Piece(); src_literal.root_piece_.set_subshape(src_literal.shape_.get()); return absl::OkStatus(); } [&](const ShapeIndex& src_index, Piece* src_piece) { if (!src_piece->subshape().IsArray()) { return; } ShapeIndex dest_index = dest_shape_index; for (int64_t i : src_index) { dest_index.push_back(i); } Piece& dest_piece = piece(dest_index); dest_piece.DeallocateBuffers(); dest_piece.MoveDataFrom(*src_piece); }); absl::Status MutableLiteralBase::CopySliceFrom( const LiteralSlice& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << shape(); TF_RET_CHECK(LayoutUtil::IsDenseArray(src_literal.shape())) << src_literal.shape(); TF_RET_CHECK(ShapeUtil::SameElementType(src_literal.shape(), shape())); TF_RET_CHECK(src_literal.shape().rank() == src_base.size()); TF_RET_CHECK(shape().rank() == dest_base.size()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, void MutableLiteralBase::PopulateR1(const tsl::core::Bitmap& values) { CHECK(shape().IsArray()); CHECK_EQ(shape().rank(), 1); CHECK_EQ(element_count(), values.bits()); CHECK_EQ(shape().element_type(), PRED); for (int64_t i = 0; i < static_cast<int64_t>(values.bits()); ++i) { Set({i}, values.get(i)); } } void MutableLiteralBase::PopulateInplaceInternal( absl::FunctionRef<void(void*, absl::Span<const int64_t>, int)> populator, bool parallel) { const Shape& this_shape = shape(); const int64_t rank = this_shape.rank(); DCHECK(LayoutUtil::IsDenseArray(this_shape)); char* const dest_base = static_cast<char*>(untyped_data()); if (rank > 0) { StrideConfig stride_config(this_shape, this_shape, this_shape.dimensions()); const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); const int64_t num_elements = ShapeUtil::ElementsIn(shape()); // If we are rank-1 and we are `parallel`, it is better to use a smaller // `step` than what `StrideConfig` does: stick the entire dimension in the // inner-most loop. if (parallel && this_shape.rank() == 1) { const int64_t thread_count = ShapeUtil::GetForEachIndexParallelThreadCount(); // Let's just divide up the array into small amounts per thread. stride_config.dest_stride = stride_config.minor_loop_size = num_elements > 32 ? std::max<int64_t>(num_elements / thread_count, 1) : num_elements; stride_config.step = {stride_config.minor_loop_size}; } auto init_function = [&](absl::Span<const int64_t> indexes, int thread_id) -> absl::StatusOr<bool> { const int64_t index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), indexes); DimensionVector minor_scan_indexes(rank, 0); std::copy(indexes.begin(), indexes.end(), minor_scan_indexes.begin()); char* dest_ptr = dest_base + index * primitive_size; char* const dest_end = dest_base + // This handles the case where minor_loop_size does not evenly divide // the most minor dimension. std::min(index + stride_config.minor_loop_size, num_elements) * primitive_size; while (dest_ptr < dest_end) { populator(dest_ptr, minor_scan_indexes, thread_id); ++minor_scan_indexes[stride_config.minor_dimension]; dest_ptr += primitive_size; } return true; }; if (parallel) { ShapeUtil::ForEachIndexParallel(this_shape, stride_config.base, stride_config.dimensions, stride_config.step, init_function); } else { ShapeUtil::ForEachIndex( this_shape, stride_config.base, stride_config.dimensions, stride_config.step, [&init_function]( absl::Span<const int64_t> indexes) -> absl::StatusOr<bool> { auto result_ignored = init_function(indexes, /*thread_id=*/-1); return true; }); } } else { // For scalars. populator(dest_base, {}, /*thread_id=*/-1); } } auto init_function = [&](absl::Span<const int64_t> indexes, int thread_id) -> absl::StatusOr<bool> { const int64_t index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), indexes); DimensionVector minor_scan_indexes(rank, 0); std::copy(indexes.begin(), indexes.end(), minor_scan_indexes.begin()); char* dest_ptr = dest_base + index * primitive_size; char* const dest_end = dest_base + // This handles the case where minor_loop_size does not evenly divide // the most minor dimension. std::min(index + stride_config.minor_loop_size, num_elements) * primitive_size; while (dest_ptr < dest_end) { populator(dest_ptr, minor_scan_indexes, thread_id); ++minor_scan_indexes[stride_config.minor_dimension]; dest_ptr += primitive_size; } return true; }; [&init_function]( absl::Span<const int64_t> indexes) -> absl::StatusOr<bool> { auto result_ignored = init_function(indexes, /*thread_id=*/-1); return true; }); absl::Status MutableLiteralBase::PopulateInplace( absl::FunctionRef<void(void*, absl::Span<const int64_t>)> populator) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); PopulateInplaceInternal( [&](void* dest, absl::Span<const int64_t> indexes, int /*thread_id*/) { return populator(dest, indexes); }, /*parallel=*/false); return absl::OkStatus(); } absl::Status MutableLiteralBase::PopulateInplaceParallel( absl::FunctionRef<void(void*, absl::Span<const int64_t>, int)> populator) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); PopulateInplaceInternal(populator, /*parallel=*/element_count() > 32); return absl::OkStatus(); } Literal LiteralBase::Relayout(const Layout& new_layout, const ShapeIndex& shape_index) const { // Create new shape with 'new_layout' set at the given shape index. Shape new_shape = shape(); Shape* subshape = ShapeUtil::GetMutableSubshape(&new_shape, shape_index); TF_CHECK_OK(LayoutUtil::ValidateLayoutForShape(new_layout, *subshape)); *subshape->mutable_layout() = new_layout; // LINT.IfChange // s4 literals are stored in uint8_t/int8_t, therefore element_size_in_bits // must be removed. if (subshape->layout().element_size_in_bits() == 4) { subshape->mutable_layout()->set_element_size_in_bits(0); } // LINT.ThenChange(//tensorflow/compiler/xla/types.h) Literal result(new_shape); TF_CHECK_OK(result.CopyFrom(*this)); return result; } Literal LiteralBase::Relayout(const Shape& shape_with_layout) const { CHECK(ShapeUtil::Compatible(shape_with_layout, shape())) << "Given shape_with_layout " << ShapeUtil::HumanString(shape_with_layout) << " not compatible with literal shape " << ShapeUtil::HumanString(shape()); Literal result = CreateFromShape(shape_with_layout); ShapeUtil::ForEachSubshape( result.shape(), [this, &result](const Shape& subshape, const ShapeIndex& index) { if (subshape.IsArray()) { TF_CHECK_OK(result.CopyFrom(*this, /*dest_shape_index=*/index, /*src_shape_index=*/index)); } }); return result; } [this, &result](const Shape& subshape, const ShapeIndex& index) { if (subshape.IsArray()) { TF_CHECK_OK(result.CopyFrom(*this, /*dest_shape_index=*/index, /*src_shape_index=*/index)); } }); Literal LiteralBase::ToBoundedDynamic(const Shape& bounded_shape) const { CHECK(bounded_shape.is_dynamic()); Literal result(bounded_shape); ShapeUtil::ForEachSubshape( shape(), [&](const Shape& subshape, const ShapeIndex& index) { if (!subshape.IsArray()) { return; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (bounded_shape.is_dynamic_dimension(i)) { result.SetDynamicSize(i, subshape.dimensions(i)); } } }); TF_CHECK_OK(result.CopyFrom(*this, {}, {}, /*only_dynamic_bound=*/true)); return result; } shape(), [&](const Shape& subshape, const ShapeIndex& index) { if (!subshape.IsArray()) { return; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (bounded_shape.is_dynamic_dimension(i)) { result.SetDynamicSize(i, subshape.dimensions(i)); } } }); Literal LiteralBase::ToStatic() const { // Create new shape with 'new_layout' set at the given shape index. Shape new_shape = shape(); ShapeUtil::ForEachMutableSubshape( &new_shape, [this](Shape* subshape, const ShapeIndex& index) { if (!subshape->IsArray()) { return; } for (int64_t i = 0; i < subshape->rank(); ++i) { // GetDynamicSize has a 32-bit return type and may truncate static // dimensions, so make sure to skip. if (!subshape->is_dynamic_dimension(i)) continue; subshape->set_dynamic_dimension(i, false); subshape->set_dimensions(i, GetDynamicSize(i, index)); } }); Literal result(new_shape); TF_CHECK_OK(result.CopyFrom(*this, {}, {}, /*only_dynamic_bound=*/true)); return result; } &new_shape, [this](Shape* subshape, const ShapeIndex& index) { if (!subshape->IsArray()) { return; } for (int64_t i = 0; i < subshape->rank(); ++i) { // GetDynamicSize has a 32-bit return type and may truncate static // dimensions, so make sure to skip. if (!subshape->is_dynamic_dimension(i)) continue; subshape->set_dynamic_dimension(i, false); subshape->set_dimensions(i, GetDynamicSize(i, index)); } }); absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { absl::StatusOr<Literal> LiteralBase::Broadcast( const Shape& result_shape, absl::Span<const int64_t> dimensions) const { const LiteralBase& src = *this; const Shape& src_shape = shape(); if (!src_shape.IsArray()) { return InvalidArgument("Broadcast only supports arrays."); } const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(src_shape.element_type()); switch (primitive_size) { case 0: return BroadcastHelper<0>(src, src_shape, result_shape, dimensions); case 1: return BroadcastHelper<1>(src, src_shape, result_shape, dimensions); case 2: return BroadcastHelper<2>(src, src_shape, result_shape, dimensions); case 4: return BroadcastHelper<4>(src, src_shape, result_shape, dimensions); case 8: return BroadcastHelper<8>(src, src_shape, result_shape, dimensions); case 16: return BroadcastHelper<16>(src, src_shape, result_shape, dimensions); default: LOG(FATAL) << "Unhandled primitive size " << primitive_size; return InvalidArgument("Unhandled primitive size"); break; } } absl::StatusOr<Literal> LiteralBase::Reshape( absl::Span<const int64_t> dimensions) const { if (!LayoutUtil::IsDenseArray(shape())) { return InvalidArgument("Reshape is only supported for dense arrays."); } if (shape().is_dynamic()) { // TODO(b/243182930): We should consider supporting dynamic reshape. return Unimplemented("Dynamic reshape is not implemented."); } Literal output; if (!LayoutUtil::IsMonotonicWithDim0Major(shape().layout())) { output = Relayout(LayoutUtil::GetDefaultLayoutForRank(shape().rank())); } else { output = Clone(); } // Because the layout is monotonic, we can simply reuse the same sequence of // values without changing their order. *output.mutable_shape_do_not_use() = ShapeUtil::MakeShape(shape().element_type(), dimensions); int64_t elements_before = ShapeUtil::ElementsIn(shape()); int64_t elements_after = ShapeUtil::ElementsIn(output.shape()); if (elements_before != elements_after) { return InvalidArgument( "Shapes before and after Literal::Reshape have different numbers " "of elements: %s vs %s.", ShapeUtil::HumanString(shape()), ShapeUtil::HumanString(output.shape())); } return std::move(output); } Literal LiteralBase::Transpose(absl::Span<const int64_t> permutation) const { CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); CHECK(shape().rank() == permutation.size() && IsPermutation(permutation)) << "Given permutation is not a permutation of dimension numbers"; // To transpose the array, we just permute the dimensions and layout, and // do a straight memory copy of the raw data set. // This is considerably faster than iterating over every array element using // the EachCell<>() and Set<>() APIs. Shape permuted_shape = ShapeUtil::PermuteDimensions(permutation, shape()); // Replace the layout with one affine to this shape, such that a // transpose operation can be performed by leaving the flat values // representation intact. // For example, consider the shape F32[11,8]{1,0} under a {1,0} permutation. // The shape with affine layout resulting from that operation will be // F32[8,11]{0,1}, since it leaves the original most minor (the 8 sized), the // most minor. // // Essentially, given MinMaj(Di) the position of the Di dimension within the // minor to major vector, and given T(Di) the index that the original Di // dimension has within the transposed array, a layout is affine if // MinMaj(Di) == TMinMaj(T(Di)), with TMinMaj() being the minor to major // vector of the affine layout. std::vector<int64_t> inverse_permutation = InversePermutation(permutation); CHECK(LayoutUtil::IsDenseArray(permuted_shape)); Layout* layout = permuted_shape.mutable_layout(); layout->clear_minor_to_major(); for (auto index : LayoutUtil::MinorToMajor(shape())) { layout->add_minor_to_major(inverse_permutation[index]); } Literal new_literal(permuted_shape); if (shape().is_dynamic()) { for (int64_t i = 0; i < shape().rank(); i++) { if (shape().is_dynamic_dimension(i)) { // Set the dynamic size of any dynamic dimension in the transposed // literal. new_literal.SetDynamicSize(inverse_permutation[i], GetDynamicSize(i)); } } } DCHECK_EQ(ShapeUtil::ByteSizeOf(new_literal.shape()), ShapeUtil::ByteSizeOf(shape())); std::memcpy(new_literal.untyped_data(), untyped_data(), size_bytes()); return new_literal; } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( Literal LiteralBase::Slice(absl::Span<const int64_t> start_indices, absl::Span<const int64_t> limit_indices) const { CHECK(shape().IsArray()) << "tuple is not supported for slice"; DimensionVector result_dimensions; for (int64_t dnum = 0; dnum < shape().rank(); ++dnum) { CHECK_GE(start_indices[dnum], 0); CHECK_LE(limit_indices[dnum], shape().dimensions(dnum)) << "dnum = " << dnum; int64_t dimension = limit_indices[dnum] - start_indices[dnum]; CHECK_GE(dimension, 0) << "dnum = " << dnum; result_dimensions.push_back(dimension); } auto result_shape = ShapeUtil::MakeShapeWithDenseLayout( shape().element_type(), result_dimensions, LayoutUtil::MinorToMajor(shape())); ShapeUtil::CopyDynamicDimensions(&result_shape, shape()); Literal result_literal(result_shape); primitive_util::ArrayTypeSwitch<void>( [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; return SliceInternal<NativeT>(*this, start_indices, result_literal); }, result_shape.element_type()); return result_literal; } Literal LiteralBase::Clone() const { Literal result(shape()); TF_CHECK_OK(result.CopyFrom(*this)); return result; } std::unique_ptr<Literal> LiteralBase::CloneToUnique() const { auto result = std::make_unique<Literal>(shape()); TF_CHECK_OK(result->CopyFrom(*this)); return result; } bool LiteralBase::IsDetermined(const ShapeIndex& shape_index) const { return piece(shape_index).IsDetermined(); } bool LiteralBase::IsKnown(const ShapeIndex& shape_index) const { return piece(shape_index).IsKnown(); } std::string LiteralBase::GetAsString(absl::Span<const int64_t> multi_index, const ShapeIndex& shape_index) const { const Shape& subshape = ShapeUtil::GetSubshape(shape(), shape_index); CHECK(LayoutUtil::IsDenseArray(subshape)); return primitive_util::ArrayTypeSwitch<std::string>( [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, subshape.element_type()); } [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, std::optional<int64_t> LiteralBase::GetIntegralAsS64( absl::Span<const int64_t> multi_index) const { CHECK(LayoutUtil::IsDenseArray(shape())); return primitive_util::PrimitiveTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, std::optional<double> LiteralBase::GetAsDouble( absl::Span<const int64_t> multi_index) const { const Shape& s = shape(); CHECK(LayoutUtil::IsDenseArray(s)); return primitive_util::PrimitiveTypeSwitch<std::optional<double>>( [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, s.element_type()); } [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, std::optional<double> LiteralBase::GetSumAsDouble( absl::Span<const int64_t> linear_indices) const { const Shape& s = shape(); CHECK(LayoutUtil::IsDenseArray(s)); if (!primitive_util::IsFloatingPointType(s.element_type())) { return std::nullopt; } return primitive_util::FloatingPointTypeSwitch<double>( [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, s.element_type()); } [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, std::optional<complex128> LiteralBase::GetAsComplex128( absl::Span<const int64_t> multi_index) const { return primitive_util::PrimitiveTypeSwitch<std::optional<complex128>>( [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, absl::Status MutableLiteralBase::SetIntegralAsS64( absl::Span<const int64_t> multi_index, int64_t value) { CHECK(LayoutUtil::IsDenseArray(shape())); return primitive_util::PrimitiveTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, absl::Status MutableLiteralBase::SetFromDouble( absl::Span<const int64_t> multi_index, double value) { CHECK(LayoutUtil::IsDenseArray(shape())); if (!primitive_util::IsFloatingPointType(shape().element_type())) { return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); } primitive_util::FloatingPointTypeSwitch<void>( [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, shape().element_type()); return absl::OkStatus(); } [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, void PrintShape(bool print_layout, const Shape& shape, Printer* printer) { if (print_layout) { ShapeUtil::PrintHumanStringWithLayout(printer, shape); } else { ShapeUtil::PrintHumanString(printer, shape); } } void TuplePrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); printer->Append(oneline ? "( " : "(\n"); for (int i = 0; i < ShapeUtil::TupleElementCount(subshape); ++i) { ShapeIndex element_index = shape_index; element_index.push_back(i); if (i > 0) printer->Append(oneline ? ", " : ",\n"); PrintHelper(literal, element_index, print_shape, print_layout, oneline, printer); } printer->Append(oneline ? " )" : "\n)"); } void DenseArrayPrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); int64_t rank = subshape.rank(); const absl::string_view linebreak = oneline ? " " : "\n"; std::function<void(absl::Span<const int64_t> dimensions, std::vector<int64_t>*)> print_recursive = [&](absl::Span<const int64_t> dimensions, std::vector<int64_t>* accum_indices) { // dimensions.size() decreases by 1 at each recursive call, // and accum_indices->size() increases by 1. // Their sum is equal to the rank of the tensor. CHECK_EQ(rank, dimensions.size() + accum_indices->size()); auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; if (dimensions.empty()) { // Display predicates as 0s and 1s so that the string is more dense. std::string elem; if (subshape.element_type() == PRED && rank > 0) { elem = literal.Get<bool>(*accum_indices, shape_index) ? "1" : "0"; } else { elem = literal.GetAsString(*accum_indices, shape_index); } printer->Append(elem); } else { printer->Append(brace_to_string("{")); for (int i = 0; i < dimensions[0]; ++i) { accum_indices->push_back(i); print_recursive(dimensions.subspan(1), accum_indices); accum_indices->pop_back(); if (i < dimensions[0] - 1) { printer->Append(","); printer->Append(dimensions.size() > 1 ? linebreak : " "); } } printer->Append(brace_to_string("}")); } }; if (print_shape) { PrintShape(print_layout, subshape, printer); if (subshape.is_dynamic()) { printer->Append("("); for (int64_t i = 0; i < subshape.dimensions_size(); ++i) { printer->Append(literal.GetDynamicSize(i, shape_index)); if (i < subshape.dimensions_size() - 1) { printer->Append(","); } } printer->Append(")"); } printer->Append(" "); } std::vector<int64_t> indices = {}; std::vector<int64_t> dimensions; dimensions.reserve(subshape.rank()); for (int64_t i = 0; i < subshape.rank(); ++i) { dimensions.push_back(literal.GetDynamicSize(i, shape_index)); } print_recursive(dimensions, &indices); } print_recursive = [&](absl::Span<const int64_t> dimensions, std::vector<int64_t>* accum_indices) { // dimensions.size() decreases by 1 at each recursive call, // and accum_indices->size() increases by 1. // Their sum is equal to the rank of the tensor. CHECK_EQ(rank, dimensions.size() + accum_indices->size()); auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; if (dimensions.empty()) { // Display predicates as 0s and 1s so that the string is more dense. std::string elem; if (subshape.element_type() == PRED && rank > 0) { elem = literal.Get<bool>(*accum_indices, shape_index) ? "1" : "0"; } else { elem = literal.GetAsString(*accum_indices, shape_index); } printer->Append(elem); } else { printer->Append(brace_to_string("{")); for (int i = 0; i < dimensions[0]; ++i) { accum_indices->push_back(i); print_recursive(dimensions.subspan(1), accum_indices); accum_indices->pop_back(); if (i < dimensions[0] - 1) { printer->Append(","); printer->Append(dimensions.size() > 1 ? linebreak : " "); } } printer->Append(brace_to_string("}")); } }; auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; void PrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); CHECK(LayoutUtil::HasLayout(literal.shape())); CHECK(LayoutUtil::HasLayout(subshape)); if (subshape.IsTuple()) { TuplePrintHelper(literal, shape_index, print_shape, print_layout, oneline, printer); } else if (subshape.IsToken()) { printer->Append("token"); } else { CHECK(LayoutUtil::IsDenseArray(subshape)); if (literal.IsKnown(shape_index)) { DenseArrayPrintHelper(literal, shape_index, print_shape, print_layout, oneline, printer); } else { PrintShape(print_layout, subshape, printer); printer->Append(" "); if (literal.IsDetermined(shape_index)) { printer->Append("unknown"); } else { printer->Append("undetermined"); } } } } void LiteralBase::Print(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/false, /*oneline=*/false, printer); } void LiteralBase::PrintOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/false, /*oneline=*/true, printer); } void LiteralBase::PrintWithoutShape(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/false, /*print_layout=*/false, /*oneline=*/false, printer); } void LiteralBase::PrintWithoutShapeOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/false, /*print_layout=*/false, /*oneline=*/true, printer); } void LiteralBase::PrintWithLayout(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/true, /*oneline=*/false, printer); } void LiteralBase::PrintWithLayoutOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/true, /*oneline=*/true, printer); } std::string LiteralBase::ToString() const { StringPrinter printer; Print(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringOneline() const { StringPrinter printer; PrintOneline(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithoutShape() const { StringPrinter printer; PrintWithoutShape(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithoutShapeOneline() const { StringPrinter printer; PrintWithoutShapeOneline(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithLayout() const { StringPrinter printer; PrintWithLayout(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithLayoutOneline() const { StringPrinter printer; PrintWithLayoutOneline(&printer); return std::move(printer).ToString(); } void LiteralBase::EachCellAsString( absl::FunctionRef<void(absl::Span<const int64_t> indices, const std::string& value)> per_cell) const { if (ShapeUtil::IsZeroElementArray(shape())) { return; } auto indices = IndexUtil::LinearIndexToMultidimensionalIndex( shape(), /*linear_index=*/0); do { per_cell(indices, GetAsString(indices)); } while (IndexUtil::BumpIndices(shape(), absl::MakeSpan(indices))); } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { absl::StatusOr<Literal> ConvertSwitch(const LiteralBase& literal, PrimitiveType primitive_dest_type) { TF_RET_CHECK(LayoutUtil::IsDenseArray(literal.shape())); if (literal.shape().element_type() == primitive_dest_type) { return literal.Clone(); } // Source Array type requirement is ensured by IsDenseArray before. if (!primitive_util::IsArrayType(primitive_dest_type) || !primitive_util::IsArrayType(literal.shape().element_type())) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(literal.shape().element_type()), PrimitiveType_Name(primitive_dest_type)); } // At this point, we know both src & dst are array types, while src is not // complex type, so we can allocate the result literal here to avoid // duplicating it N^2 times in the conversion implementation. Literal result( ShapeUtil::ChangeElementType(literal.shape(), primitive_dest_type)); TF_RETURN_IF_ERROR(primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { return ConvertIfDestTypeMatches<primitive_type_constant>(literal, result); }, literal.shape().element_type())); return result; } absl::StatusOr<Literal> LiteralBase::Convert( PrimitiveType primitive_dest_type) const { return ConvertSwitch(*this, primitive_dest_type); } absl::StatusOr<Literal> LiteralBase::BitcastConvert( const Shape& dest_shape) const { if (ShapeUtil::ByteSizeOf(dest_shape) != ShapeUtil::ByteSizeOf(shape())) { return InvalidArgument( "Can not bitcast-convert from shape %s to a shape of different size %s", shape().ToString(), dest_shape.ToString()); } if (dest_shape.IsTuple() || shape().IsTuple()) { return InvalidArgument( "bitcast-convert is not valid for tuple shapes %s->%s", shape().ToString(), dest_shape.ToString()); } if (shape().is_dynamic() || dest_shape.is_dynamic()) { return InvalidArgument( "bitcast-convert is not valid for dynamic shape %s->%s", shape().ToString(), dest_shape.ToString()); } Literal out(dest_shape); std::memcpy(out.root_piece_.buffer(), root_piece().buffer(), root_piece().size_bytes_dense()); // Perform the reshape on little endian encoding even on big endian machines. if constexpr (!kLittleEndian) { // Swap byte ordering as per the input data type. size_t input_elem_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); TF_RETURN_IF_ERROR(tsl::ByteSwapArray( const_cast<char*>(out.root_piece().buffer()), input_elem_size, out.root_piece().size_bytes_dense() / input_elem_size)); // Swap byte ordering as per the output data type. size_t output_elem_size = ShapeUtil::ByteSizeOfPrimitiveType(dest_shape.element_type()); TF_RETURN_IF_ERROR(tsl::ByteSwapArray( const_cast<char*>(out.root_piece().buffer()), output_elem_size, out.root_piece().size_bytes_dense() / output_elem_size)); } return out; } absl::StatusOr<Literal> LiteralBase::ConvertToShape( const Shape& dest_shape) const { if (!dest_shape.IsTuple()) { return Convert(dest_shape.element_type()); } std::vector<Literal> elements; const auto tuple_element_count = ShapeUtil::TupleElementCount(shape()); elements.reserve(tuple_element_count); for (int i = 0; i < tuple_element_count; ++i) { auto element = LiteralSlice(*this, {i}); TF_ASSIGN_OR_RETURN( auto new_element, element.ConvertToShape(ShapeUtil::GetSubshape(dest_shape, {i}))); elements.push_back(std::move(new_element)); } return MutableLiteralBase::MoveIntoTuple(absl::MakeSpan(elements)); } /* static */ Literal MutableLiteralBase::MoveIntoTuple( absl::Span<Literal> elements) { std::vector<const Shape*> element_shapes; element_shapes.reserve(elements.size()); for (const Literal& element : elements) { element_shapes.push_back(&element.shape()); } Literal literal(ShapeUtil::MakeTupleShapeWithPtrs(element_shapes), /*allocate_arrays=*/false); for (int i = 0, end = elements.size(); i < end; ++i) { TF_CHECK_OK( literal.MoveFrom(std::move(elements[i]), /*dest_shape_index=*/{i})); } return literal; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualDynamicSize( const LiteralBase::Piece& other) const { DCHECK(ShapeUtil::Compatible(subshape(), other.subshape())); if (subshape().is_static()) { return true; } for (int64_t i = 0; i < subshape().rank(); ++i) { if (GetDynamicSize(i) != other.GetDynamicSize(i)) { return false; } } return true; } bool LiteralBase::Piece::EqualElements(const LiteralBase::Piece& other) const { if (subshape().is_static() && ShapeUtil::Equal(subshape(), other.subshape()) && subshape().IsArray()) { CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(size_bytes_dense(), other.size_bytes_dense()); if (primitive_util::IsSubByteNonPredType(subshape().element_type())) { CHECK(!primitive_util::IsFloatingPointType(subshape().element_type())); auto one_array = buffer(); auto two_array = other.buffer(); const int bits_per_element = primitive_util::BitWidth(subshape().element_type()); const uint8_t mask = LsbMask<uint8_t>(bits_per_element); for (int64_t i = 0; i < size_bytes_dense(); ++i) { if ((one_array[i] & mask) != (two_array[i] & mask)) return false; } return true; } return memcmp(buffer(), other.buffer(), size_bytes_dense()) == 0; } std::vector<int64_t> multi_index; return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeSrcT = NativeTypeOf<primitive_type_constant>; return EqualElementsInternal<NativeSrcT>(other, &multi_index); }, subshape().element_type()); } bool LiteralBase::Equal(const LiteralBase& other, bool layout_sensitive) const { // Checking the structure of tuple literals. Checks for dense arrays are // performed below. if (!ShapeUtil::EqualStructure(shape(), other.shape())) { return false; } return root_piece().ForEachSubpieceWithBool([&](const ShapeIndex& index, const Piece& piece) { const Piece& other_piece = other.piece(index); const Shape& subshape = piece.subshape(); const Shape& other_subshape = other_piece.subshape(); if (subshape.element_type() != other_subshape.element_type()) { return false; } if (!piece.subshape().IsArray()) { return true; } if (subshape.rank() != other_subshape.rank()) { return false; } if (layout_sensitive && (subshape.layout() != other_subshape.layout())) { return false; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (piece.GetDynamicSize(i) != other_piece.GetDynamicSize(i)) { return false; } } if (!piece.EqualElements(other_piece)) { return false; } return true; }); } return root_piece().ForEachSubpieceWithBool([&](const ShapeIndex& index, const Piece& piece) { const Piece& other_piece = other.piece(index); const Shape& subshape = piece.subshape(); const Shape& other_subshape = other_piece.subshape(); if (subshape.element_type() != other_subshape.element_type()) { return false; } if (!piece.subshape().IsArray()) { return true; } if (subshape.rank() != other_subshape.rank()) { return false; } if (layout_sensitive && (subshape.layout() != other_subshape.layout())) { return false; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (piece.GetDynamicSize(i) != other_piece.GetDynamicSize(i)) { return false; } } if (!piece.EqualElements(other_piece)) { return false; } return true; }); static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(std::complex<T> a, std::complex<T> b) { return EqualIncludingNan(a.real(), b.real()) && EqualIncludingNan(a.imag(), b.imag()); } static bool EqualIncludingNan(std::complex<T> a, std::complex<T> b) { return EqualIncludingNan(a.real(), b.real()) && EqualIncludingNan(a.imag(), b.imag()); } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } bool Literal::Piece::IsAll(const Literal& scalar) const { CHECK(ShapeUtil::IsScalar(scalar.shape())) << scalar.shape().ToString(); if (!subshape().IsArray()) { return false; } CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(subshape().element_type(), scalar.shape().element_type()); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, subshape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, int64_t Literal::Piece::CountAll(const Literal& scalar) const { CHECK(ShapeUtil::IsScalar(scalar.shape())) << scalar.shape().ToString(); if (!subshape().IsArray()) { return 0; } CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(subshape().element_type(), scalar.shape().element_type()); return primitive_util::ArrayTypeSwitch<int64_t>( [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, subshape().element_type()); } [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { bool LiteralBase::IsAll(const Literal& scalar) const { return root_piece().IsAll(scalar); } bool LiteralBase::IsAll(int8_t value) const { if (!shape().IsArray()) { return false; } PrimitiveType ty = shape().element_type(); if (primitive_util::IsFloatingPointType(ty)) { return IsAllFloatImpl(value, /*round_value=*/false); } if (primitive_util::IsUnsignedIntegralType(ty) && value < 0) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllFloat(float value) const { return IsAllFloatImpl(value, /*round_value=*/true); } bool LiteralBase::IsAllFloatImpl(float value, bool round_value) const { PrimitiveType ty = shape().element_type(); if (!primitive_util::IsFloatingPointType(ty)) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::FloatingPointTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllComplex(complex64 value) const { PrimitiveType ty = shape().element_type(); if (!primitive_util::IsComplexType(ty)) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::ComplexTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllFirst() const { if (!shape().IsArray()) { return false; } // Empty shapes are not all the first element since there is no first element. if (ShapeUtil::IsZeroElementArray(shape())) { return false; } absl::InlinedVector<int64_t, 4> start_indices(/*n=*/shape().rank(), 0); absl::InlinedVector<int64_t, 4> end_indices(/*n=*/shape().rank(), 1); Literal first = Slice(start_indices, end_indices); return IsAll(first.Reshape({}).value()); } bool LiteralBase::IsR1Iota() const { if (!shape().IsArray()) { return false; } CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); if (shape().rank() != 1) { return false; } return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, shape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, std::optional<int64_t> LiteralBase::IsR1StridedIota() const { if (!shape().IsArray() || shape().rank() != 1) { return std::nullopt; } CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); const int64_t elements = ShapeUtil::ElementsIn(shape()); const PrimitiveType type = shape().element_type(); if (elements <= 1 || !primitive_util::IsIntegralType(type)) { return std::nullopt; } return primitive_util::IntegralTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, bool LiteralBase::IsZero(absl::Span<const int64_t> indices) const { CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, shape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void LiteralBase::Piece::set_array_value_state(ArrayValueState state) { array_value_state_ = state; } LiteralBase::ArrayValueState LiteralBase::Piece::get_array_value_state() const { return array_value_state_; } void LiteralBase::Piece::WriteToProto(LiteralProto* proto) const { *proto->mutable_shape() = subshape().ToProto(); switch (subshape().element_type()) { case PRED: CopyToRepeatedField(proto->mutable_preds(), data<bool>()); break; case U2: *proto->mutable_u2s() = std::string( reinterpret_cast<const char*>(data<u2>().data()), size_bytes_dense()); break; case U4: *proto->mutable_u4s() = std::string( reinterpret_cast<const char*>(data<u4>().data()), size_bytes_dense()); break; case U8: proto->set_u8s(static_cast<const unsigned char*>(data<uint8_t>().data()), element_count()); break; case U16: *proto->mutable_u16s() = std::string(reinterpret_cast<const char*>(data<uint16_t>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_u16s()); } break; case U32: CopyToRepeatedField(proto->mutable_u32s(), data<uint32_t>()); break; case U64: CopyToRepeatedField(proto->mutable_u64s(), data<uint64_t>()); break; case S2: *proto->mutable_s2s() = std::string( reinterpret_cast<const char*>(data<s2>().data()), size_bytes_dense()); break; case S4: *proto->mutable_s4s() = std::string( reinterpret_cast<const char*>(data<s4>().data()), size_bytes_dense()); break; case S8: proto->set_s8s(static_cast<const signed char*>(data<int8_t>().data()), element_count()); break; case S16: *proto->mutable_s16s() = std::string(reinterpret_cast<const char*>(data<int16_t>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_s16s()); } break; case S32: CopyToRepeatedField(proto->mutable_s32s(), data<int32_t>()); break; case S64: CopyToRepeatedField(proto->mutable_s64s(), data<int64_t>()); break; case F8E5M2: *proto->mutable_f8e5m2s() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e5m2>().data()), size_bytes_dense()); break; case F8E4M3FN: *proto->mutable_f8e4m3fns() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3fn>().data()), size_bytes_dense()); break; case F8E4M3B11FNUZ: *proto->mutable_f8e4m3b11fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3b11fnuz>().data()), size_bytes_dense()); break; case F8E5M2FNUZ: *proto->mutable_f8e5m2fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e5m2fnuz>().data()), size_bytes_dense()); break; case F8E4M3FNUZ: *proto->mutable_f8e4m3fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3fnuz>().data()), size_bytes_dense()); break; case F16: *proto->mutable_f16s() = std::string(reinterpret_cast<const char*>(data<half>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_f16s()); } break; case BF16: *proto->mutable_bf16s() = std::string(reinterpret_cast<const char*>(data<bfloat16>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_bf16s()); } break; case F32: CopyToRepeatedField(proto->mutable_f32s(), data<float>()); break; case F64: CopyToRepeatedField(proto->mutable_f64s(), data<double>()); break; case C64: for (complex64 value : data<complex64>()) { proto->add_c64s(value.real()); proto->add_c64s(value.imag()); } break; case C128: for (complex128 value : data<complex128>()) { proto->add_c128s(value.real()); proto->add_c128s(value.imag()); } break; case TUPLE: case TOKEN: // Nothing to do but assign the shape which is done above. return; default: // TODO(b/111551621): Support serializing more PrimitiveTypes. LOG(FATAL) << "Unhandled primitive type " << PrimitiveType_Name(subshape().element_type()); } } const void* LiteralBase::Piece::untyped_data() const { DCHECK(LayoutUtil::IsDenseArray(subshape())) << ShapeUtil::HumanString(subshape()); return buffer(); } void* LiteralBase::Piece::untyped_data() { DCHECK(LayoutUtil::IsDenseArray(subshape())) << ShapeUtil::HumanString(subshape()); return buffer(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status LiteralBase::Piece::CopyFromProto(const LiteralProto& proto) { // These conditions should have been checked in // MutableLiteralBase::CreateFromProto. TF_RET_CHECK(proto.has_shape()); Shape shape(proto.shape()); TF_RET_CHECK(LayoutUtil::HasLayout(shape)); TF_RET_CHECK(ShapeUtil::Equal(shape, subshape())); switch (subshape().element_type()) { case PRED: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<bool>(), proto.preds())); break; case S2: { const std::string& s(proto.s2s()); TF_RET_CHECK(data<s2>().size() * sizeof(s2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case S4: { const std::string& s(proto.s4s()); TF_RET_CHECK(data<s4>().size() * sizeof(s4) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case S8: { auto s8_data = data<int8_t>(); TF_RET_CHECK(proto.s8s().size() == s8_data.size()); std::copy(proto.s8s().begin(), proto.s8s().end(), s8_data.begin()); break; } case S16: { const std::string& s(proto.s16s()); TF_RET_CHECK(data<int16_t>().size() * sizeof(int16_t) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case S32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<int32_t>(), proto.s32s())); break; case S64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<int64_t>(), proto.s64s())); break; case U2: { const std::string& s(proto.u2s()); TF_RET_CHECK(data<u2>().size() * sizeof(u2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case U4: { const std::string& s(proto.u4s()); TF_RET_CHECK(data<u4>().size() * sizeof(u4) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case U8: { auto u8_data = data<uint8_t>(); TF_RET_CHECK(proto.u8s().size() == u8_data.size()); std::copy(proto.u8s().begin(), proto.u8s().end(), u8_data.begin()); break; } case U16: { const std::string& s(proto.u16s()); TF_RET_CHECK(data<uint16_t>().size() * sizeof(uint16_t) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case U32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<uint32_t>(), proto.u32s())); break; case U64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<uint64_t>(), proto.u64s())); break; case F8E5M2: { const std::string& s(proto.f8e5m2s()); TF_RET_CHECK(data<tsl::float8_e5m2>().size() * sizeof(tsl::float8_e5m2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3FN: { const std::string& s(proto.f8e4m3fns()); TF_RET_CHECK(data<tsl::float8_e4m3fn>().size() * sizeof(tsl::float8_e4m3fn) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3B11FNUZ: { const std::string& s(proto.f8e4m3b11fnuzs()); TF_RET_CHECK(data<tsl::float8_e4m3b11fnuz>().size() * sizeof(tsl::float8_e4m3b11fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E5M2FNUZ: { const std::string& s(proto.f8e5m2fnuzs()); TF_RET_CHECK(data<tsl::float8_e5m2fnuz>().size() * sizeof(tsl::float8_e5m2fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3FNUZ: { const std::string& s(proto.f8e4m3fnuzs()); TF_RET_CHECK(data<tsl::float8_e4m3fnuz>().size() * sizeof(tsl::float8_e4m3fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F16: { const std::string& s(proto.f16s()); TF_RET_CHECK(data<half>().size() * sizeof(half) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case BF16: { const std::string& s(proto.bf16s()); TF_RET_CHECK(data<bfloat16>().size() * sizeof(bfloat16) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case F32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<float>(), proto.f32s())); break; case F64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<double>(), proto.f64s())); break; case C64: { auto complex_data = data<complex64>(); TF_RET_CHECK(proto.c64s_size() == complex_data.size() * 2); for (int64_t i = 0; i < complex_data.size(); ++i) { complex_data[i] = complex64{proto.c64s(i * 2), proto.c64s(i * 2 + 1)}; } break; } case C128: { auto complex_data = data<complex128>(); const int64_t complex_data_size_doubled = complex_data.size() * 2; TF_RET_CHECK(proto.c128s_size() == complex_data_size_doubled); for (int64_t i = 0, end = complex_data.size(); i < end; ++i) { complex_data[i] = complex128{proto.c128s(i * 2), proto.c128s(i * 2 + 1)}; } break; } case TUPLE: return InvalidArgument("Should not be called on tuple shapes: %s", ShapeUtil::HumanString(subshape())); default: return InvalidArgument("Is called on unsupported shape: %s", ShapeUtil::HumanString(subshape())); } return absl::OkStatus(); } bool LiteralBase::Piece::IsKnown() const { if (array_value_state_ != ArrayValueState::kKnown) { return false; } if (subshape().IsTuple()) { bool are_all_leaf_arrays_known = true; ForEachSubpiece([&are_all_leaf_arrays_known](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_known &= piece.IsKnown(); }); return are_all_leaf_arrays_known; } return true; } ForEachSubpiece([&are_all_leaf_arrays_known](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_known &= piece.IsKnown(); }); bool LiteralBase::Piece::IsDetermined() const { if (array_value_state_ == ArrayValueState::kUndetermined) { return false; } if (subshape().IsTuple()) { bool are_all_leaf_arrays_determined = true; ForEachSubpiece([&are_all_leaf_arrays_determined](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_determined &= piece.IsDetermined(); }); return are_all_leaf_arrays_determined; } return true; } ForEachSubpiece([&are_all_leaf_arrays_determined](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_determined &= piece.IsDetermined(); }); LiteralProto LiteralBase::ToProto() const { LiteralProto proto; root_piece().ForEachSubpiece( [&](const ShapeIndex& index, const Piece& piece) { LiteralProto* proto_piece = &proto; for (int64_t i : index) { while (proto_piece->tuple_literals_size() <= i) { proto_piece->add_tuple_literals(); } proto_piece = proto_piece->mutable_tuple_literals(i); } piece.WriteToProto(proto_piece); }); return proto; } [&](const ShapeIndex& index, const Piece& piece) { LiteralProto* proto_piece = &proto; for (int64_t i : index) { while (proto_piece->tuple_literals_size() <= i) { proto_piece->add_tuple_literals(); } proto_piece = proto_piece->mutable_tuple_literals(i); } piece.WriteToProto(proto_piece); }); const void* LiteralBase::untyped_data(const ShapeIndex& shape_index) const { return piece(shape_index).untyped_data(); } void* MutableLiteralBase::untyped_data(const ShapeIndex& shape_index) { return piece(shape_index).untyped_data(); } int64_t LiteralBase::size_bytes(const ShapeIndex& shape_index) const { return piece(shape_index).size_bytes_dense(); } std::string LiteralBase::GetR1U8AsString() const { CHECK(shape().IsArray()); CHECK_EQ(shape().rank(), 1); CHECK_EQ(shape().element_type(), U8); return std::string(absl::bit_cast<const char*>(data<uint8_t>().data()), ShapeUtil::ElementsIn(shape())); } void MutableBorrowingLiteral::CopyPieceSubtree(const Shape& shape, const Piece* src_piece, Piece* dest_piece) { DCHECK(ShapeUtil::Equal(src_piece->subshape(), dest_piece->subshape())) << "src_piece has shape: " << ShapeUtil::HumanString(src_piece->subshape()) << "dest_piece has shape: " << ShapeUtil::HumanString(dest_piece->subshape()); dest_piece->set_array_value_state(src_piece->get_array_value_state()); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); Piece child_piece; child_piece.set_subshape(&subshape); CopyPieceSubtree(subshape, &src_piece->child(i), &child_piece); dest_piece->emplace_back(std::move(child_piece)); } } else if (shape.IsArray()) { dest_piece->set_buffer(const_cast<char*>(src_piece->buffer())); } } MutableLiteralBase::~MutableLiteralBase() = default; MutableBorrowingLiteral::MutableBorrowingLiteral( const MutableBorrowingLiteral& literal) : MutableLiteralBase() { shape_ = literal.shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.root_piece(), root_piece_); } MutableBorrowingLiteral& MutableBorrowingLiteral::operator=( const MutableBorrowingLiteral& literal) { shape_ = literal.shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.root_piece(), root_piece_); return *this; } MutableBorrowingLiteral::MutableBorrowingLiteral(MutableLiteralBase* literal) : MutableLiteralBase() { shape_ = literal->shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal->root_piece(), root_piece_); } MutableBorrowingLiteral::MutableBorrowingLiteral( MutableBorrowingLiteral literal, const ShapeIndex& view_root) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(literal.piece(view_root).subshape()); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.piece(view_root), root_piece_); } MutableBorrowingLiteral::MutableBorrowingLiteral(const char* src_buf_ptr, const Shape& shape) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(shape); CHECK(LayoutUtil::HasLayout(*shape_)); CHECK(!shape_->IsTuple()); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); root_piece_->set_buffer(const_cast<char*>(src_buf_ptr)); } MutableBorrowingLiteral::MutableBorrowingLiteral(absl::Span<char*> src_buf_ptrs, const Shape& shape) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(shape); if (!shape_->IsTuple()) { CHECK_EQ(src_buf_ptrs.size(), 1); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); root_piece_->set_buffer(const_cast<char*>(src_buf_ptrs[0])); } else { CHECK(!ShapeUtil::IsNestedTuple(*shape_)); CHECK_EQ(src_buf_ptrs.size(), ShapeUtil::TupleElementCount(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); for (int i = 0; i < src_buf_ptrs.size(); ++i) { Piece child_piece; const auto& src_shape = shape_->tuple_shapes(i); CHECK(src_shape.IsArray()); child_piece.set_subshape(&src_shape); child_piece.set_buffer(src_buf_ptrs[i]); root_piece_->emplace_back(std::move(child_piece)); } } } MutableBorrowingLiteral::MutableBorrowingLiteral(ShapeTree<char*> src_buf_ptrs) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(src_buf_ptrs.shape()); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); BuildPieceSubtree(*shape_, root_piece_); root_piece_->ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); } [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); MutableBorrowingLiteral::~MutableBorrowingLiteral() { if (root_piece_ != nullptr) { delete root_piece_; } } LiteralSlice::LiteralSlice(const LiteralBase& literal) : LiteralBase(), root_piece_(&literal.root_piece()) {} LiteralSlice::LiteralSlice(const LiteralBase& literal, const ShapeIndex& view_root) : LiteralBase(), root_piece_(&literal.piece(view_root)) {} BorrowingLiteral::BorrowingLiteral(const char* src_buf_ptr, const Shape& shape) : LiteralBase(), shape_(std::make_unique<Shape>(shape)) { CHECK(shape_->IsArray()); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); root_piece_.set_buffer(const_cast<char*>(src_buf_ptr)); } BorrowingLiteral::BorrowingLiteral(absl::Span<const char* const> src_buf_ptrs, const Shape& shape) : LiteralBase(), shape_(std::make_unique<Shape>(shape)) { CHECK(shape_->IsTuple()); CHECK(!ShapeUtil::IsNestedTuple(*shape_)); CHECK_EQ(src_buf_ptrs.size(), ShapeUtil::TupleElementCount(*shape_)); root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); BuildPieceSubtree(*shape_, &root_piece_); for (int i = 0, end = src_buf_ptrs.size(); i < end; ++i) { const auto& src_shape = shape_->tuple_shapes(i); CHECK(src_shape.IsArray()); root_piece_.child(i).set_buffer(const_cast<char*>(src_buf_ptrs[i])); } } BorrowingLiteral::BorrowingLiteral(ShapeTree<const char*> src_buf_ptrs) : LiteralBase(), shape_(std::make_unique<Shape>(src_buf_ptrs.shape())) { root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); BuildPieceSubtree(*shape_, &root_piece_); root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); } [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); });
#include "xla/literal.h" #include <algorithm> #include <cmath> #include <complex> #include <cstdint> #include <functional> #include <limits> #include <random> #include <string> #include <tuple> #include <utility> #include <vector> #include "absl/base/casts.h" #include "absl/hash/hash.h" #include "absl/random/random.h" #include "absl/status/status.h" #include "absl/strings/match.h" #include "absl/types/span.h" #include "xla/array.h" #include "xla/array2d.h" #include "xla/array3d.h" #include "xla/array4d.h" #include "xla/index_util.h" #include "xla/layout.h" #include "xla/layout_util.h" #include "xla/literal_util.h" #include "xla/primitive_util.h" #include "xla/shape.h" #include "xla/shape_tree.h" #include "xla/shape_util.h" #include "xla/test.h" #include "xla/types.h" #include "xla/util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/errors.h" #include "tsl/platform/logging.h" // IWYU pragma: keep #include "tsl/platform/macros.h" #include "tsl/platform/ml_dtypes.h" #include "tsl/platform/statusor.h" #include "tsl/platform/test_benchmark.h" class LiteralUtilTest : public ::testing::Test { protected: LiteralUtilTest() { Array4D<float> arr4d({ // clang-format off { // i0=0 { // i1=0 {1, 2, 3}, // i2=0 {4, 5, 6}, // i2=1 {7, 8, 9}, // i2=2 }, { // i1=1 {11, 12, 13}, {14, 15, 16}, {17, 18, 19}, }, }, { // i0=1 { // i1=0 {101, 102, 103}, {104, 105, 106}, {107, 108, 109}, }, { // i1=1 {201, 202, 203}, // i2=0 {204, 205, 206}, // i2=1 {207, 208, 209}, // i2=2 }, }, // clang-format on }); layout_r2_dim0major_ = LayoutUtil::MakeLayout({1, 0}); layout_r2_dim0minor_ = LayoutUtil::MakeLayout({0, 1}); layout_r3_dim0major_ = LayoutUtil::MakeLayout({2, 1, 0}); layout_r3_dim0minor_ = LayoutUtil::MakeLayout({0, 1, 2}); layout_r4_dim0major_ = LayoutUtil::MakeLayout({3, 2, 1, 0}); layout_r4_dim0minor_ = LayoutUtil::MakeLayout({0, 1, 2, 3}); literal_r4_2x2x3x3_dim0major_ = LiteralUtil::CreateR4FromArray4DWithLayout<float>(arr4d, layout_r4_dim0major_); literal_r4_2x2x3x3_dim0minor_ = LiteralUtil::CreateR4FromArray4DWithLayout<float>(arr4d, layout_r4_dim0minor_); } Layout layout_r2_dim0major_; Layout layout_r2_dim0minor_; Layout layout_r3_dim0major_; Layout layout_r3_dim0minor_; Layout layout_r4_dim0major_; Layout layout_r4_dim0minor_; Literal literal_r4_2x2x3x3_dim0major_; Literal literal_r4_2x2x3x3_dim0minor_; }; TEST_F(LiteralUtilTest, C64Equality) { // Test equality with tuples. auto vector = LiteralUtil::CreateR1<complex64>({{1.0, 2.0}, {3.0, 4.0}}); // Tuple with the same elements. One element is shared with the original // tuple, the other is a clone of the element in the original tuple. auto vector_clone = LiteralUtil::CreateR1<complex64>({{1.0, 2.0}, {3.0, 4.0}}); EXPECT_EQ(vector, vector_clone); auto vector_reversed = LiteralUtil::CreateR1<complex64>({{3.0, 4.0}, {1.0, 2.0}}); EXPECT_NE(vector, vector_reversed); }
LiteralUtilTest_ConvertIfTypesMatch
xla/literal_test.cc
bool LiteralProtoHasValues(const LiteralProto& proto) { return !proto.s2s().empty() || !proto.s4s().empty() || !proto.s8s().empty() || !proto.s16s().empty() || proto.s32s_size() || proto.s64s_size() || !proto.u2s().empty() || !proto.u4s().empty() || !proto.u8s().empty() || !proto.u16s().empty() || proto.u32s_size() || proto.u64s_size() || !proto.f8e5m2s().empty() || !proto.f8e4m3fns().empty() || !proto.f8e4m3b11fnuzs().empty() || !proto.f8e5m2fnuzs().empty() || !proto.f8e4m3fnuzs().empty() || !proto.f16s().empty() || !proto.bf16s().empty() || proto.f32s_size() || proto.f64s_size() || proto.c64s_size() || proto.c128s_size() || proto.preds_size() || proto.tuple_literals_size(); } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { const Shape& NilShape() { static const Shape* shape = new Shape(TUPLE, {}, {}, {}); return *shape; } const Shape* TryInternShape(const Shape& shape) { if (shape.IsTuple() && shape.tuple_shapes_size() == 0) { return &NilShape(); } if (shape.IsArray() && shape.dimensions_size() == 0 && shape.is_static() && shape.layout().tiles_size() == 0 && shape.layout().memory_space() == 0) { return &ScalarShape(shape.element_type()); } return nullptr; } StrideConfig::StrideConfig(const Shape& source_shape, const Shape& dest_shape, absl::Span<const int64_t> dimensions) : dimensions(dimensions), base(dimensions.size(), 0), step(dimensions.size(), 1) { if (!dimensions.empty()) { // Selects the shape with the largest minor dimension as the one upon // which to run the tight stride loop. if (dimensions[LayoutUtil::Minor(source_shape.layout(), 0)] >= dimensions[LayoutUtil::Minor(dest_shape.layout(), 0)]) { minor_dimension = LayoutUtil::Minor(source_shape.layout(), 0); dest_stride = IndexUtil::GetDimensionStride(dest_shape, minor_dimension); } else { minor_dimension = LayoutUtil::Minor(dest_shape.layout(), 0); source_stride = IndexUtil::GetDimensionStride(source_shape, minor_dimension); } minor_loop_size = dimensions[minor_dimension]; step[minor_dimension] = minor_loop_size; } } LiteralBase::~LiteralBase() = default; const Shape& LiteralBase::shape() const { return root_piece().subshape(); } const char* LiteralBase::Piece::buffer() const { // std::visit is avoided here due to its code size issues. if (auto* r = std::get_if<DenseRep>(&rep_)) { return r->data; } if (auto* r = std::get_if<DenseInlinedRep>(&rep_)) { return r->data; } DCHECK(std::holds_alternative<TupleRep>(rep_) || std::holds_alternative<Uninitialized>(rep_)); return nullptr; } const LiteralBase::Piece& LiteralBase::piece( const ShapeIndex& shape_index) const { const Piece* piece = &root_piece(); for (const auto i : shape_index) { DCHECK_GE(i, 0); DCHECK_LT(i, piece->children_size()); piece = &piece->child(i); } return *piece; } std::ostream& operator<<(std::ostream& out, const Literal& literal) { out << literal.ToString(); return out; } Shape* MutableLiteralBase::mutable_shape_do_not_use() { const Shape* const_shape = shape_.get(); if (!shape_.OwnsPtr()) { shape_ = MaybeOwningShapePtr(std::make_unique<Shape>(*shape_)); } Shape* shape = shape_.get_mutable(); if (shape != const_shape) { std::function<void(const Shape&, Piece*)> set_piece_shapes = [&set_piece_shapes](const Shape& shape, Piece* piece) { piece->set_subshape(&shape); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); set_piece_shapes(subshape, &piece->child(i)); } } }; set_piece_shapes(*shape, &mutable_root_piece()); } return shape; } [&set_piece_shapes](const Shape& shape, Piece* piece) { piece->set_subshape(&shape); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); set_piece_shapes(subshape, &piece->child(i)); } } }; Literal::Literal() : Literal(NilShape()) {} Literal::Literal(const Shape& shape) : Literal(shape, /*allocate_arrays=*/true) {} void Literal::SetShape(const Shape& shape) { Shape shape_storage; const Shape* shape_ptr = &shape; if (LayoutUtil::HasCustomElementSizeInBits(shape)) { shape_storage = shape; shape_storage.mutable_layout()->set_element_size_in_bits(0); shape_ptr = &shape_storage; } if (const Shape* intered_shape_ptr = TryInternShape(*shape_ptr)) { shape_ = intered_shape_ptr; } else { shape_ = std::make_unique<Shape>(*shape_ptr); } } void Literal::SetPiece(const Shape& shape, Piece* piece, bool allocate_arrays, ArrayValueState leaf_array_value_state) { if (shape.IsTuple()) { for (const Shape& subshape : shape.tuple_shapes()) { Piece child_piece; child_piece.set_subshape(&subshape); SetPiece(subshape, &child_piece, allocate_arrays, leaf_array_value_state); piece->emplace_back(std::move(child_piece)); } } else if (shape.IsArray()) { DCHECK(LayoutUtil::IsDenseArray(shape)) << "literal array storage is currently only supported for dense " "arrays: " << shape; piece->set_array_value_state(leaf_array_value_state); if (leaf_array_value_state == LiteralBase::ArrayValueState::kKnown && allocate_arrays) { piece->AllocateBuffers(); } } } Literal::Literal(const Shape& shape, bool allocate_arrays, ArrayValueState leaf_array_value_state) : MutableLiteralBase() { SetShape(shape); CHECK(leaf_array_value_state != ArrayValueState::kKnown || LayoutUtil::HasLayout(*shape_)); root_piece_.set_subshape(shape_.get()); CHECK(&root_piece_.subshape() == shape_.get()); SetPiece(*shape_, &root_piece_, allocate_arrays, leaf_array_value_state); } Literal::~Literal() { DeallocateBuffers(); } void Literal::DeallocateBuffers() { root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { piece->DeallocateBuffers(); }); } Literal::Literal(Literal&& other) : MutableLiteralBase() { *this = std::move(other); } Literal& Literal::operator=(Literal&& other) { DCHECK(&other.root_piece_.subshape() == other.shape_.get()); using std::swap; swap(shape_, other.shape_); swap(root_piece_, other.root_piece_); DCHECK(&root_piece_.subshape() == shape_.get()); return *this; } Literal LiteralBase::CreateFromShape(const Shape& shape) { Literal literal(shape); literal.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (piece->subshape().IsArray()) { memset(piece->untyped_data(), 0, piece->size_bytes_dense()); } }); return literal; } [&](const ShapeIndex& index, Piece* piece) { if (piece->subshape().IsArray()) { memset(piece->untyped_data(), 0, piece->size_bytes_dense()); } }); Literal LiteralBase::CreateFromShapeWithUnknownLeafArrays(const Shape& shape) { Literal literal(shape, /*allocate_arrays=*/false, ArrayValueState::kUnknown); return literal; } Literal LiteralBase::CreateFromShapeWithUndeterminedLeafArrays( const Shape& shape) { Literal literal(shape, /*allocate_arrays=*/false, ArrayValueState::kUndetermined); return literal; } int32_t LiteralBase::GetDynamicSize(int64_t dim_index) const { return GetDynamicSize(dim_index, {}); } int32_t LiteralBase::GetDynamicSize(int64_t dim_index, const ShapeIndex& shape_index) const { return piece(shape_index).GetDynamicSize(dim_index); } std::optional<int64_t> LiteralBase::GetFirstInteger() const { if (!primitive_util::IsIntegralType(shape().element_type())) { return std::nullopt; } return primitive_util::IntegralTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, void LiteralBase::BuildPieceSubtree(const Shape& shape, Piece* piece) { CHECK(shape.IsTuple()); for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); Piece child_piece; child_piece.set_subshape(&subshape); if (subshape.IsTuple()) { BuildPieceSubtree(subshape, &child_piece); } piece->emplace_back(std::move(child_piece)); } } absl::Status LiteralBase::SerializeToString(std::string* output) const { ShapeProto shape_proto = shape().ToProto(); TF_ASSIGN_OR_RETURN(int64_t size, ShapeUtil::SerializedSizeWithProto(shape(), shape_proto)); output->resize(size); return SerializeWithShapeProto(shape_proto, output->data()); } absl::StatusOr<std::string> LiteralBase::SerializeAsString() const { std::string result; TF_RETURN_IF_ERROR(SerializeToString(&result)); return std::move(result); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { void MutableLiteralBase::CopyElementFrom(const LiteralSlice& src_literal, absl::Span<const int64_t> src_index, absl::Span<const int64_t> dest_index) { DCHECK(LayoutUtil::IsDenseArray(shape())); DCHECK_EQ(shape().element_type(), src_literal.shape().element_type()); const int64_t src_linear_index = IndexUtil::MultidimensionalIndexToLinearIndex(src_literal.shape(), src_index); const int64_t dest_linear_index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), dest_index); const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); char* dest_address = static_cast<char*>(untyped_data()) + dest_linear_index * primitive_size; const char* source_address = static_cast<const char*>(src_literal.untyped_data()) + src_linear_index * primitive_size; if (dest_address != source_address) { memcpy(dest_address, source_address, primitive_size); } } /* static */ absl::StatusOr<Literal> MutableLiteralBase::CreateFromProto( const LiteralProto& proto, bool prohibit_empty_literal) { if (!proto.has_shape()) { return InvalidArgument("LiteralProto has no shape"); } Shape shape(proto.shape()); if (ShapeUtil::HasPrimitiveType(shape, OPAQUE_TYPE)) { return InvalidArgument( "Literal shape cannot include OPAQUE_TYPE sub-shape"); } if (!LayoutUtil::HasLayout(shape)) { return InvalidArgument("LiteralProto has no layout"); } if (LayoutUtil::IsSparseArray(shape)) { return Unimplemented("Sparse literals are not supported"); } TF_RETURN_IF_ERROR(ShapeUtil::ValidateShapeWithOptionalLayout(shape)); Literal literal(shape); TF_RETURN_IF_ERROR(literal.root_piece_.ForEachMutableSubpieceWithStatus( [&](const ShapeIndex& index, Piece* piece) -> absl::Status { const LiteralProto* proto_element = &proto; for (int64_t i : index) { CHECK(i < proto_element->tuple_literals_size()); proto_element = &proto_element->tuple_literals(i); } if (piece->subshape().IsTuple()) { if (proto_element->tuple_literals_size() != ShapeUtil::TupleElementCount(piece->subshape())) { return InvalidArgument( "Expected %d tuple elements in LiteralProto, has %d", ShapeUtil::TupleElementCount(piece->subshape()), proto_element->tuple_literals_size()); } return absl::OkStatus(); } if (piece->subshape().element_type() == TOKEN) { return absl::OkStatus(); } CHECK(piece->subshape().IsArray()); // When prohibit_empty_literal is false (allowing literal with no // values), only copy from proto if the literal proto has values. This // mode is used for a learned cost model. if (prohibit_empty_literal || LiteralProtoHasValues(*proto_element)) { TF_RETURN_IF_ERROR(piece->CopyFromProto(*proto_element)); } return absl::OkStatus(); })); return std::move(literal); } TF_RETURN_IF_ERROR(literal.root_piece_.ForEachMutableSubpieceWithStatus( Literal Literal::SubLiteral(ShapeIndexView shape_index) { if (!shape_index.empty()) { auto decomposed = this->DecomposeTuple(); return decomposed.at(shape_index.front()) .SubLiteral(shape_index.subspan(1)); } else { return std::move(*this); } } std::vector<Literal> Literal::DecomposeTuple() { CHECK(shape().IsTuple()); std::vector<Literal> elements; const auto tuple_element_count = ShapeUtil::TupleElementCount(shape()); elements.reserve(tuple_element_count); for (int i = 0; i < tuple_element_count; ++i) { elements.push_back(Literal(ShapeUtil::GetSubshape(shape(), {i}), /*allocate_arrays=*/false)); Literal& element = elements.back(); element.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* dest_piece) { if (dest_piece->subshape().IsTuple()) { return; } ShapeIndex src_index = {i}; for (int64_t j : index) { src_index.push_back(j); } Piece& src_piece = piece(src_index); // Move the respective buffer over to the element Literal. dest_piece->MoveDataFrom(src_piece); }); } // Set this literal to be nil-shaped. *this = Literal(); return elements; } [&](const ShapeIndex& index, Piece* dest_piece) { if (dest_piece->subshape().IsTuple()) { return; } ShapeIndex src_index = {i}; for (int64_t j : index) { src_index.push_back(j); } Piece& src_piece = piece(src_index); // Move the respective buffer over to the element Literal. dest_piece->MoveDataFrom(src_piece); }); void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } int32_t LiteralBase::Piece::GetDynamicSize(int64_t dim_index) const { CHECK(LayoutUtil::IsDenseArray(subshape())); if (!subshape_->is_dynamic_dimension(dim_index)) { // This is a static dimension, return size. return subshape_->dimensions(dim_index); } return dynamic_size_buffer()[dim_index]; } void LiteralBase::Piece::SetDynamicSize(int64_t dim_index, int32_t size) { CHECK(LayoutUtil::IsDenseArray(subshape())); CHECK(subshape_->is_dynamic_dimension(dim_index)); dynamic_size_buffer()[dim_index] = size; } void LiteralBase::Piece::AllocateBuffers() { const int64_t bytes = total_bytes_dense(); if (bytes > kMaxInlinedBytes) { CHECK_EQ(buffer(), nullptr); rep_.emplace<DenseRep>(); set_buffer( static_cast<char*>(tsl::port::AlignedMalloc(bytes, kMinimumAlignment))); } else { rep_.emplace<DenseInlinedRep>(); } } void LiteralBase::Piece::DeallocateBuffers() { if (auto* array_rep = GetDenseRep()) { tsl::port::AlignedFree(array_rep->data); rep_.emplace<Uninitialized>(); } } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } absl::Status LiteralBase::Piece::CopyFrom(const LiteralBase::Piece& src, bool only_dynamic_bound) { CHECK(subshape_ != nullptr); CHECK(src.subshape_ != nullptr); CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK(LayoutUtil::IsDenseArray(src.subshape())) << __func__ << " is only supported for dense arrays: " << src.subshape(); if (!only_dynamic_bound) { CHECK(ShapeUtil::Compatible(subshape(), src.subshape())); } if (src.array_value_state_ == ArrayValueState::kUnknown || src.array_value_state_ == ArrayValueState::kUndetermined) { if (array_value_state_ == ArrayValueState::kKnown) { DeallocateBuffers(); } array_value_state_ = src.array_value_state_; return absl::OkStatus(); } else { CHECK(src.array_value_state_ == ArrayValueState::kKnown); if (array_value_state_ == ArrayValueState::kUndetermined || array_value_state_ == ArrayValueState::kUnknown) { AllocateBuffers(); } array_value_state_ = src.array_value_state_; } if (ShapeUtil::Equal(subshape(), src.subshape())) { // If the layouts are equal it's faster just to memcpy. memcpy(buffer(), src.buffer(), src.size_bytes_dense()); } else { std::vector<int64_t> origin(subshape().rank(), 0); primitive_util::ArrayTypeSwitch<void>( [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, subshape().element_type()); } DCHECK_EQ(dynamic_size_buffer_bytes(), src.dynamic_size_buffer_bytes()); if (subshape().is_dynamic() && src.subshape().is_dynamic()) { memcpy(dynamic_size_buffer(), src.dynamic_size_buffer(), src.dynamic_size_buffer_bytes()); } return absl::OkStatus(); } [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, void MutableLiteralBase::SetDynamicSize(int64_t dim_index, int32_t size) { return SetDynamicSize(dim_index, {}, size); } void MutableLiteralBase::SetDynamicSize(int64_t dim_index, const ShapeIndex& shape_index, int32_t size) { Shape* subshape = ShapeUtil::GetMutableSubshape(mutable_shape_do_not_use(), shape_index); CHECK(LayoutUtil::IsDenseArray(*subshape)) << __func__ << " is only supported for dense arrays: " << *subshape; CHECK_GE(subshape->dimensions(dim_index), size); subshape->set_dynamic_dimension(dim_index, true); CHECK_EQ(&piece(shape_index).subshape(), subshape); piece(shape_index).SetDynamicSize(dim_index, size); } absl::Status MutableLiteralBase::CopyFrom(const LiteralSlice& src_literal, const ShapeIndex& dest_shape_index, const ShapeIndex& src_shape_index, bool only_dynamic_bound) { const Shape& dest_subshape = ShapeUtil::GetSubshape(shape(), dest_shape_index); const Shape& src_subshape = ShapeUtil::GetSubshape(src_literal.shape(), src_shape_index); if (only_dynamic_bound) { auto& bound_shape = dest_subshape.is_static() ? src_subshape : dest_subshape; auto& compact_shape = dest_subshape.is_static() ? dest_subshape : src_subshape; CHECK(ShapeUtil::DynamicShapeIsCompatible(compact_shape, bound_shape)) << compact_shape.ToString() << " vs " << bound_shape.ToString(); } else { if (!ShapeUtil::Compatible(dest_subshape, src_subshape)) { return InvalidArgument( "Destination subshape incompatible with source subshape: %s vs %s", ShapeUtil::HumanString(dest_subshape), ShapeUtil::HumanString(src_subshape)); } } return mutable_root_piece().ForEachMutableSubpieceWithStatus( [&](const ShapeIndex& index, Piece* piece) { if (!piece->subshape().IsArray()) { return absl::OkStatus(); } // Determine if this index is in the part of this literal that we want // to copy over from src_literal. bool in_subtree_to_copy = true; for (int i = 0; i < dest_shape_index.size(); ++i) { if (index[i] != dest_shape_index[i]) { in_subtree_to_copy = false; break; } } if (!in_subtree_to_copy) { return absl::OkStatus(); } // Construct the index of the corresponding piece in the source literal. ShapeIndex src_piece_index = src_shape_index; for (int64_t i = dest_shape_index.size(), end = index.size(); i < end; ++i) { src_piece_index.push_back(index[i]); } TF_RETURN_IF_ERROR( piece->CopyFrom(src_literal.piece(src_piece_index), /*only_dynamic_bound=*/only_dynamic_bound)); return absl::OkStatus(); }); } [&](const ShapeIndex& index, Piece* piece) { if (!piece->subshape().IsArray()) { return absl::OkStatus(); } // Determine if this index is in the part of this literal that we want // to copy over from src_literal. bool in_subtree_to_copy = true; for (int i = 0; i < dest_shape_index.size(); ++i) { if (index[i] != dest_shape_index[i]) { in_subtree_to_copy = false; break; } } if (!in_subtree_to_copy) { return absl::OkStatus(); } // Construct the index of the corresponding piece in the source literal. ShapeIndex src_piece_index = src_shape_index; for (int64_t i = dest_shape_index.size(), end = index.size(); i < end; ++i) { src_piece_index.push_back(index[i]); } TF_RETURN_IF_ERROR( piece->CopyFrom(src_literal.piece(src_piece_index), /*only_dynamic_bound=*/only_dynamic_bound)); return absl::OkStatus(); }); absl::Status Literal::MoveFrom(Literal&& src_literal, const ShapeIndex& dest_shape_index) { const Shape& dest_subshape = ShapeUtil::GetSubshape(shape(), dest_shape_index); if (!ShapeUtil::Equal(dest_subshape, src_literal.shape())) { return InvalidArgument( "Destination subshape not equal to source shape: %s vs %s", ShapeUtil::HumanString(dest_subshape), ShapeUtil::HumanString(src_literal.shape())); } src_literal.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& src_index, Piece* src_piece) { if (!src_piece->subshape().IsArray()) { return; } ShapeIndex dest_index = dest_shape_index; for (int64_t i : src_index) { dest_index.push_back(i); } Piece& dest_piece = piece(dest_index); dest_piece.DeallocateBuffers(); dest_piece.MoveDataFrom(*src_piece); }); src_literal.shape_ = MaybeOwningShapePtr(&NilShape()); src_literal.root_piece_ = Piece(); src_literal.root_piece_.set_subshape(src_literal.shape_.get()); return absl::OkStatus(); } [&](const ShapeIndex& src_index, Piece* src_piece) { if (!src_piece->subshape().IsArray()) { return; } ShapeIndex dest_index = dest_shape_index; for (int64_t i : src_index) { dest_index.push_back(i); } Piece& dest_piece = piece(dest_index); dest_piece.DeallocateBuffers(); dest_piece.MoveDataFrom(*src_piece); }); absl::Status MutableLiteralBase::CopySliceFrom( const LiteralSlice& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << shape(); TF_RET_CHECK(LayoutUtil::IsDenseArray(src_literal.shape())) << src_literal.shape(); TF_RET_CHECK(ShapeUtil::SameElementType(src_literal.shape(), shape())); TF_RET_CHECK(src_literal.shape().rank() == src_base.size()); TF_RET_CHECK(shape().rank() == dest_base.size()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, void MutableLiteralBase::PopulateR1(const tsl::core::Bitmap& values) { CHECK(shape().IsArray()); CHECK_EQ(shape().rank(), 1); CHECK_EQ(element_count(), values.bits()); CHECK_EQ(shape().element_type(), PRED); for (int64_t i = 0; i < static_cast<int64_t>(values.bits()); ++i) { Set({i}, values.get(i)); } } void MutableLiteralBase::PopulateInplaceInternal( absl::FunctionRef<void(void*, absl::Span<const int64_t>, int)> populator, bool parallel) { const Shape& this_shape = shape(); const int64_t rank = this_shape.rank(); DCHECK(LayoutUtil::IsDenseArray(this_shape)); char* const dest_base = static_cast<char*>(untyped_data()); if (rank > 0) { StrideConfig stride_config(this_shape, this_shape, this_shape.dimensions()); const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); const int64_t num_elements = ShapeUtil::ElementsIn(shape()); // If we are rank-1 and we are `parallel`, it is better to use a smaller // `step` than what `StrideConfig` does: stick the entire dimension in the // inner-most loop. if (parallel && this_shape.rank() == 1) { const int64_t thread_count = ShapeUtil::GetForEachIndexParallelThreadCount(); // Let's just divide up the array into small amounts per thread. stride_config.dest_stride = stride_config.minor_loop_size = num_elements > 32 ? std::max<int64_t>(num_elements / thread_count, 1) : num_elements; stride_config.step = {stride_config.minor_loop_size}; } auto init_function = [&](absl::Span<const int64_t> indexes, int thread_id) -> absl::StatusOr<bool> { const int64_t index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), indexes); DimensionVector minor_scan_indexes(rank, 0); std::copy(indexes.begin(), indexes.end(), minor_scan_indexes.begin()); char* dest_ptr = dest_base + index * primitive_size; char* const dest_end = dest_base + // This handles the case where minor_loop_size does not evenly divide // the most minor dimension. std::min(index + stride_config.minor_loop_size, num_elements) * primitive_size; while (dest_ptr < dest_end) { populator(dest_ptr, minor_scan_indexes, thread_id); ++minor_scan_indexes[stride_config.minor_dimension]; dest_ptr += primitive_size; } return true; }; if (parallel) { ShapeUtil::ForEachIndexParallel(this_shape, stride_config.base, stride_config.dimensions, stride_config.step, init_function); } else { ShapeUtil::ForEachIndex( this_shape, stride_config.base, stride_config.dimensions, stride_config.step, [&init_function]( absl::Span<const int64_t> indexes) -> absl::StatusOr<bool> { auto result_ignored = init_function(indexes, /*thread_id=*/-1); return true; }); } } else { // For scalars. populator(dest_base, {}, /*thread_id=*/-1); } } auto init_function = [&](absl::Span<const int64_t> indexes, int thread_id) -> absl::StatusOr<bool> { const int64_t index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), indexes); DimensionVector minor_scan_indexes(rank, 0); std::copy(indexes.begin(), indexes.end(), minor_scan_indexes.begin()); char* dest_ptr = dest_base + index * primitive_size; char* const dest_end = dest_base + // This handles the case where minor_loop_size does not evenly divide // the most minor dimension. std::min(index + stride_config.minor_loop_size, num_elements) * primitive_size; while (dest_ptr < dest_end) { populator(dest_ptr, minor_scan_indexes, thread_id); ++minor_scan_indexes[stride_config.minor_dimension]; dest_ptr += primitive_size; } return true; }; [&init_function]( absl::Span<const int64_t> indexes) -> absl::StatusOr<bool> { auto result_ignored = init_function(indexes, /*thread_id=*/-1); return true; }); absl::Status MutableLiteralBase::PopulateInplace( absl::FunctionRef<void(void*, absl::Span<const int64_t>)> populator) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); PopulateInplaceInternal( [&](void* dest, absl::Span<const int64_t> indexes, int /*thread_id*/) { return populator(dest, indexes); }, /*parallel=*/false); return absl::OkStatus(); } absl::Status MutableLiteralBase::PopulateInplaceParallel( absl::FunctionRef<void(void*, absl::Span<const int64_t>, int)> populator) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); PopulateInplaceInternal(populator, /*parallel=*/element_count() > 32); return absl::OkStatus(); } Literal LiteralBase::Relayout(const Layout& new_layout, const ShapeIndex& shape_index) const { // Create new shape with 'new_layout' set at the given shape index. Shape new_shape = shape(); Shape* subshape = ShapeUtil::GetMutableSubshape(&new_shape, shape_index); TF_CHECK_OK(LayoutUtil::ValidateLayoutForShape(new_layout, *subshape)); *subshape->mutable_layout() = new_layout; // LINT.IfChange // s4 literals are stored in uint8_t/int8_t, therefore element_size_in_bits // must be removed. if (subshape->layout().element_size_in_bits() == 4) { subshape->mutable_layout()->set_element_size_in_bits(0); } // LINT.ThenChange(//tensorflow/compiler/xla/types.h) Literal result(new_shape); TF_CHECK_OK(result.CopyFrom(*this)); return result; } Literal LiteralBase::Relayout(const Shape& shape_with_layout) const { CHECK(ShapeUtil::Compatible(shape_with_layout, shape())) << "Given shape_with_layout " << ShapeUtil::HumanString(shape_with_layout) << " not compatible with literal shape " << ShapeUtil::HumanString(shape()); Literal result = CreateFromShape(shape_with_layout); ShapeUtil::ForEachSubshape( result.shape(), [this, &result](const Shape& subshape, const ShapeIndex& index) { if (subshape.IsArray()) { TF_CHECK_OK(result.CopyFrom(*this, /*dest_shape_index=*/index, /*src_shape_index=*/index)); } }); return result; } [this, &result](const Shape& subshape, const ShapeIndex& index) { if (subshape.IsArray()) { TF_CHECK_OK(result.CopyFrom(*this, /*dest_shape_index=*/index, /*src_shape_index=*/index)); } }); Literal LiteralBase::ToBoundedDynamic(const Shape& bounded_shape) const { CHECK(bounded_shape.is_dynamic()); Literal result(bounded_shape); ShapeUtil::ForEachSubshape( shape(), [&](const Shape& subshape, const ShapeIndex& index) { if (!subshape.IsArray()) { return; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (bounded_shape.is_dynamic_dimension(i)) { result.SetDynamicSize(i, subshape.dimensions(i)); } } }); TF_CHECK_OK(result.CopyFrom(*this, {}, {}, /*only_dynamic_bound=*/true)); return result; } shape(), [&](const Shape& subshape, const ShapeIndex& index) { if (!subshape.IsArray()) { return; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (bounded_shape.is_dynamic_dimension(i)) { result.SetDynamicSize(i, subshape.dimensions(i)); } } }); Literal LiteralBase::ToStatic() const { // Create new shape with 'new_layout' set at the given shape index. Shape new_shape = shape(); ShapeUtil::ForEachMutableSubshape( &new_shape, [this](Shape* subshape, const ShapeIndex& index) { if (!subshape->IsArray()) { return; } for (int64_t i = 0; i < subshape->rank(); ++i) { // GetDynamicSize has a 32-bit return type and may truncate static // dimensions, so make sure to skip. if (!subshape->is_dynamic_dimension(i)) continue; subshape->set_dynamic_dimension(i, false); subshape->set_dimensions(i, GetDynamicSize(i, index)); } }); Literal result(new_shape); TF_CHECK_OK(result.CopyFrom(*this, {}, {}, /*only_dynamic_bound=*/true)); return result; } &new_shape, [this](Shape* subshape, const ShapeIndex& index) { if (!subshape->IsArray()) { return; } for (int64_t i = 0; i < subshape->rank(); ++i) { // GetDynamicSize has a 32-bit return type and may truncate static // dimensions, so make sure to skip. if (!subshape->is_dynamic_dimension(i)) continue; subshape->set_dynamic_dimension(i, false); subshape->set_dimensions(i, GetDynamicSize(i, index)); } }); absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { absl::StatusOr<Literal> LiteralBase::Broadcast( const Shape& result_shape, absl::Span<const int64_t> dimensions) const { const LiteralBase& src = *this; const Shape& src_shape = shape(); if (!src_shape.IsArray()) { return InvalidArgument("Broadcast only supports arrays."); } const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(src_shape.element_type()); switch (primitive_size) { case 0: return BroadcastHelper<0>(src, src_shape, result_shape, dimensions); case 1: return BroadcastHelper<1>(src, src_shape, result_shape, dimensions); case 2: return BroadcastHelper<2>(src, src_shape, result_shape, dimensions); case 4: return BroadcastHelper<4>(src, src_shape, result_shape, dimensions); case 8: return BroadcastHelper<8>(src, src_shape, result_shape, dimensions); case 16: return BroadcastHelper<16>(src, src_shape, result_shape, dimensions); default: LOG(FATAL) << "Unhandled primitive size " << primitive_size; return InvalidArgument("Unhandled primitive size"); break; } } absl::StatusOr<Literal> LiteralBase::Reshape( absl::Span<const int64_t> dimensions) const { if (!LayoutUtil::IsDenseArray(shape())) { return InvalidArgument("Reshape is only supported for dense arrays."); } if (shape().is_dynamic()) { // TODO(b/243182930): We should consider supporting dynamic reshape. return Unimplemented("Dynamic reshape is not implemented."); } Literal output; if (!LayoutUtil::IsMonotonicWithDim0Major(shape().layout())) { output = Relayout(LayoutUtil::GetDefaultLayoutForRank(shape().rank())); } else { output = Clone(); } // Because the layout is monotonic, we can simply reuse the same sequence of // values without changing their order. *output.mutable_shape_do_not_use() = ShapeUtil::MakeShape(shape().element_type(), dimensions); int64_t elements_before = ShapeUtil::ElementsIn(shape()); int64_t elements_after = ShapeUtil::ElementsIn(output.shape()); if (elements_before != elements_after) { return InvalidArgument( "Shapes before and after Literal::Reshape have different numbers " "of elements: %s vs %s.", ShapeUtil::HumanString(shape()), ShapeUtil::HumanString(output.shape())); } return std::move(output); } Literal LiteralBase::Transpose(absl::Span<const int64_t> permutation) const { CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); CHECK(shape().rank() == permutation.size() && IsPermutation(permutation)) << "Given permutation is not a permutation of dimension numbers"; // To transpose the array, we just permute the dimensions and layout, and // do a straight memory copy of the raw data set. // This is considerably faster than iterating over every array element using // the EachCell<>() and Set<>() APIs. Shape permuted_shape = ShapeUtil::PermuteDimensions(permutation, shape()); // Replace the layout with one affine to this shape, such that a // transpose operation can be performed by leaving the flat values // representation intact. // For example, consider the shape F32[11,8]{1,0} under a {1,0} permutation. // The shape with affine layout resulting from that operation will be // F32[8,11]{0,1}, since it leaves the original most minor (the 8 sized), the // most minor. // // Essentially, given MinMaj(Di) the position of the Di dimension within the // minor to major vector, and given T(Di) the index that the original Di // dimension has within the transposed array, a layout is affine if // MinMaj(Di) == TMinMaj(T(Di)), with TMinMaj() being the minor to major // vector of the affine layout. std::vector<int64_t> inverse_permutation = InversePermutation(permutation); CHECK(LayoutUtil::IsDenseArray(permuted_shape)); Layout* layout = permuted_shape.mutable_layout(); layout->clear_minor_to_major(); for (auto index : LayoutUtil::MinorToMajor(shape())) { layout->add_minor_to_major(inverse_permutation[index]); } Literal new_literal(permuted_shape); if (shape().is_dynamic()) { for (int64_t i = 0; i < shape().rank(); i++) { if (shape().is_dynamic_dimension(i)) { // Set the dynamic size of any dynamic dimension in the transposed // literal. new_literal.SetDynamicSize(inverse_permutation[i], GetDynamicSize(i)); } } } DCHECK_EQ(ShapeUtil::ByteSizeOf(new_literal.shape()), ShapeUtil::ByteSizeOf(shape())); std::memcpy(new_literal.untyped_data(), untyped_data(), size_bytes()); return new_literal; } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( Literal LiteralBase::Slice(absl::Span<const int64_t> start_indices, absl::Span<const int64_t> limit_indices) const { CHECK(shape().IsArray()) << "tuple is not supported for slice"; DimensionVector result_dimensions; for (int64_t dnum = 0; dnum < shape().rank(); ++dnum) { CHECK_GE(start_indices[dnum], 0); CHECK_LE(limit_indices[dnum], shape().dimensions(dnum)) << "dnum = " << dnum; int64_t dimension = limit_indices[dnum] - start_indices[dnum]; CHECK_GE(dimension, 0) << "dnum = " << dnum; result_dimensions.push_back(dimension); } auto result_shape = ShapeUtil::MakeShapeWithDenseLayout( shape().element_type(), result_dimensions, LayoutUtil::MinorToMajor(shape())); ShapeUtil::CopyDynamicDimensions(&result_shape, shape()); Literal result_literal(result_shape); primitive_util::ArrayTypeSwitch<void>( [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; return SliceInternal<NativeT>(*this, start_indices, result_literal); }, result_shape.element_type()); return result_literal; } Literal LiteralBase::Clone() const { Literal result(shape()); TF_CHECK_OK(result.CopyFrom(*this)); return result; } std::unique_ptr<Literal> LiteralBase::CloneToUnique() const { auto result = std::make_unique<Literal>(shape()); TF_CHECK_OK(result->CopyFrom(*this)); return result; } bool LiteralBase::IsDetermined(const ShapeIndex& shape_index) const { return piece(shape_index).IsDetermined(); } bool LiteralBase::IsKnown(const ShapeIndex& shape_index) const { return piece(shape_index).IsKnown(); } std::string LiteralBase::GetAsString(absl::Span<const int64_t> multi_index, const ShapeIndex& shape_index) const { const Shape& subshape = ShapeUtil::GetSubshape(shape(), shape_index); CHECK(LayoutUtil::IsDenseArray(subshape)); return primitive_util::ArrayTypeSwitch<std::string>( [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, subshape.element_type()); } [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, std::optional<int64_t> LiteralBase::GetIntegralAsS64( absl::Span<const int64_t> multi_index) const { CHECK(LayoutUtil::IsDenseArray(shape())); return primitive_util::PrimitiveTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, std::optional<double> LiteralBase::GetAsDouble( absl::Span<const int64_t> multi_index) const { const Shape& s = shape(); CHECK(LayoutUtil::IsDenseArray(s)); return primitive_util::PrimitiveTypeSwitch<std::optional<double>>( [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, s.element_type()); } [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, std::optional<double> LiteralBase::GetSumAsDouble( absl::Span<const int64_t> linear_indices) const { const Shape& s = shape(); CHECK(LayoutUtil::IsDenseArray(s)); if (!primitive_util::IsFloatingPointType(s.element_type())) { return std::nullopt; } return primitive_util::FloatingPointTypeSwitch<double>( [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, s.element_type()); } [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, std::optional<complex128> LiteralBase::GetAsComplex128( absl::Span<const int64_t> multi_index) const { return primitive_util::PrimitiveTypeSwitch<std::optional<complex128>>( [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, absl::Status MutableLiteralBase::SetIntegralAsS64( absl::Span<const int64_t> multi_index, int64_t value) { CHECK(LayoutUtil::IsDenseArray(shape())); return primitive_util::PrimitiveTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, absl::Status MutableLiteralBase::SetFromDouble( absl::Span<const int64_t> multi_index, double value) { CHECK(LayoutUtil::IsDenseArray(shape())); if (!primitive_util::IsFloatingPointType(shape().element_type())) { return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); } primitive_util::FloatingPointTypeSwitch<void>( [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, shape().element_type()); return absl::OkStatus(); } [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, void PrintShape(bool print_layout, const Shape& shape, Printer* printer) { if (print_layout) { ShapeUtil::PrintHumanStringWithLayout(printer, shape); } else { ShapeUtil::PrintHumanString(printer, shape); } } void TuplePrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); printer->Append(oneline ? "( " : "(\n"); for (int i = 0; i < ShapeUtil::TupleElementCount(subshape); ++i) { ShapeIndex element_index = shape_index; element_index.push_back(i); if (i > 0) printer->Append(oneline ? ", " : ",\n"); PrintHelper(literal, element_index, print_shape, print_layout, oneline, printer); } printer->Append(oneline ? " )" : "\n)"); } void DenseArrayPrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); int64_t rank = subshape.rank(); const absl::string_view linebreak = oneline ? " " : "\n"; std::function<void(absl::Span<const int64_t> dimensions, std::vector<int64_t>*)> print_recursive = [&](absl::Span<const int64_t> dimensions, std::vector<int64_t>* accum_indices) { // dimensions.size() decreases by 1 at each recursive call, // and accum_indices->size() increases by 1. // Their sum is equal to the rank of the tensor. CHECK_EQ(rank, dimensions.size() + accum_indices->size()); auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; if (dimensions.empty()) { // Display predicates as 0s and 1s so that the string is more dense. std::string elem; if (subshape.element_type() == PRED && rank > 0) { elem = literal.Get<bool>(*accum_indices, shape_index) ? "1" : "0"; } else { elem = literal.GetAsString(*accum_indices, shape_index); } printer->Append(elem); } else { printer->Append(brace_to_string("{")); for (int i = 0; i < dimensions[0]; ++i) { accum_indices->push_back(i); print_recursive(dimensions.subspan(1), accum_indices); accum_indices->pop_back(); if (i < dimensions[0] - 1) { printer->Append(","); printer->Append(dimensions.size() > 1 ? linebreak : " "); } } printer->Append(brace_to_string("}")); } }; if (print_shape) { PrintShape(print_layout, subshape, printer); if (subshape.is_dynamic()) { printer->Append("("); for (int64_t i = 0; i < subshape.dimensions_size(); ++i) { printer->Append(literal.GetDynamicSize(i, shape_index)); if (i < subshape.dimensions_size() - 1) { printer->Append(","); } } printer->Append(")"); } printer->Append(" "); } std::vector<int64_t> indices = {}; std::vector<int64_t> dimensions; dimensions.reserve(subshape.rank()); for (int64_t i = 0; i < subshape.rank(); ++i) { dimensions.push_back(literal.GetDynamicSize(i, shape_index)); } print_recursive(dimensions, &indices); } print_recursive = [&](absl::Span<const int64_t> dimensions, std::vector<int64_t>* accum_indices) { // dimensions.size() decreases by 1 at each recursive call, // and accum_indices->size() increases by 1. // Their sum is equal to the rank of the tensor. CHECK_EQ(rank, dimensions.size() + accum_indices->size()); auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; if (dimensions.empty()) { // Display predicates as 0s and 1s so that the string is more dense. std::string elem; if (subshape.element_type() == PRED && rank > 0) { elem = literal.Get<bool>(*accum_indices, shape_index) ? "1" : "0"; } else { elem = literal.GetAsString(*accum_indices, shape_index); } printer->Append(elem); } else { printer->Append(brace_to_string("{")); for (int i = 0; i < dimensions[0]; ++i) { accum_indices->push_back(i); print_recursive(dimensions.subspan(1), accum_indices); accum_indices->pop_back(); if (i < dimensions[0] - 1) { printer->Append(","); printer->Append(dimensions.size() > 1 ? linebreak : " "); } } printer->Append(brace_to_string("}")); } }; auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; void PrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); CHECK(LayoutUtil::HasLayout(literal.shape())); CHECK(LayoutUtil::HasLayout(subshape)); if (subshape.IsTuple()) { TuplePrintHelper(literal, shape_index, print_shape, print_layout, oneline, printer); } else if (subshape.IsToken()) { printer->Append("token"); } else { CHECK(LayoutUtil::IsDenseArray(subshape)); if (literal.IsKnown(shape_index)) { DenseArrayPrintHelper(literal, shape_index, print_shape, print_layout, oneline, printer); } else { PrintShape(print_layout, subshape, printer); printer->Append(" "); if (literal.IsDetermined(shape_index)) { printer->Append("unknown"); } else { printer->Append("undetermined"); } } } } void LiteralBase::Print(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/false, /*oneline=*/false, printer); } void LiteralBase::PrintOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/false, /*oneline=*/true, printer); } void LiteralBase::PrintWithoutShape(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/false, /*print_layout=*/false, /*oneline=*/false, printer); } void LiteralBase::PrintWithoutShapeOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/false, /*print_layout=*/false, /*oneline=*/true, printer); } void LiteralBase::PrintWithLayout(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/true, /*oneline=*/false, printer); } void LiteralBase::PrintWithLayoutOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/true, /*oneline=*/true, printer); } std::string LiteralBase::ToString() const { StringPrinter printer; Print(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringOneline() const { StringPrinter printer; PrintOneline(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithoutShape() const { StringPrinter printer; PrintWithoutShape(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithoutShapeOneline() const { StringPrinter printer; PrintWithoutShapeOneline(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithLayout() const { StringPrinter printer; PrintWithLayout(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithLayoutOneline() const { StringPrinter printer; PrintWithLayoutOneline(&printer); return std::move(printer).ToString(); } void LiteralBase::EachCellAsString( absl::FunctionRef<void(absl::Span<const int64_t> indices, const std::string& value)> per_cell) const { if (ShapeUtil::IsZeroElementArray(shape())) { return; } auto indices = IndexUtil::LinearIndexToMultidimensionalIndex( shape(), /*linear_index=*/0); do { per_cell(indices, GetAsString(indices)); } while (IndexUtil::BumpIndices(shape(), absl::MakeSpan(indices))); } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { absl::StatusOr<Literal> ConvertSwitch(const LiteralBase& literal, PrimitiveType primitive_dest_type) { TF_RET_CHECK(LayoutUtil::IsDenseArray(literal.shape())); if (literal.shape().element_type() == primitive_dest_type) { return literal.Clone(); } // Source Array type requirement is ensured by IsDenseArray before. if (!primitive_util::IsArrayType(primitive_dest_type) || !primitive_util::IsArrayType(literal.shape().element_type())) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(literal.shape().element_type()), PrimitiveType_Name(primitive_dest_type)); } // At this point, we know both src & dst are array types, while src is not // complex type, so we can allocate the result literal here to avoid // duplicating it N^2 times in the conversion implementation. Literal result( ShapeUtil::ChangeElementType(literal.shape(), primitive_dest_type)); TF_RETURN_IF_ERROR(primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { return ConvertIfDestTypeMatches<primitive_type_constant>(literal, result); }, literal.shape().element_type())); return result; } absl::StatusOr<Literal> LiteralBase::Convert( PrimitiveType primitive_dest_type) const { return ConvertSwitch(*this, primitive_dest_type); } absl::StatusOr<Literal> LiteralBase::BitcastConvert( const Shape& dest_shape) const { if (ShapeUtil::ByteSizeOf(dest_shape) != ShapeUtil::ByteSizeOf(shape())) { return InvalidArgument( "Can not bitcast-convert from shape %s to a shape of different size %s", shape().ToString(), dest_shape.ToString()); } if (dest_shape.IsTuple() || shape().IsTuple()) { return InvalidArgument( "bitcast-convert is not valid for tuple shapes %s->%s", shape().ToString(), dest_shape.ToString()); } if (shape().is_dynamic() || dest_shape.is_dynamic()) { return InvalidArgument( "bitcast-convert is not valid for dynamic shape %s->%s", shape().ToString(), dest_shape.ToString()); } Literal out(dest_shape); std::memcpy(out.root_piece_.buffer(), root_piece().buffer(), root_piece().size_bytes_dense()); // Perform the reshape on little endian encoding even on big endian machines. if constexpr (!kLittleEndian) { // Swap byte ordering as per the input data type. size_t input_elem_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); TF_RETURN_IF_ERROR(tsl::ByteSwapArray( const_cast<char*>(out.root_piece().buffer()), input_elem_size, out.root_piece().size_bytes_dense() / input_elem_size)); // Swap byte ordering as per the output data type. size_t output_elem_size = ShapeUtil::ByteSizeOfPrimitiveType(dest_shape.element_type()); TF_RETURN_IF_ERROR(tsl::ByteSwapArray( const_cast<char*>(out.root_piece().buffer()), output_elem_size, out.root_piece().size_bytes_dense() / output_elem_size)); } return out; } absl::StatusOr<Literal> LiteralBase::ConvertToShape( const Shape& dest_shape) const { if (!dest_shape.IsTuple()) { return Convert(dest_shape.element_type()); } std::vector<Literal> elements; const auto tuple_element_count = ShapeUtil::TupleElementCount(shape()); elements.reserve(tuple_element_count); for (int i = 0; i < tuple_element_count; ++i) { auto element = LiteralSlice(*this, {i}); TF_ASSIGN_OR_RETURN( auto new_element, element.ConvertToShape(ShapeUtil::GetSubshape(dest_shape, {i}))); elements.push_back(std::move(new_element)); } return MutableLiteralBase::MoveIntoTuple(absl::MakeSpan(elements)); } /* static */ Literal MutableLiteralBase::MoveIntoTuple( absl::Span<Literal> elements) { std::vector<const Shape*> element_shapes; element_shapes.reserve(elements.size()); for (const Literal& element : elements) { element_shapes.push_back(&element.shape()); } Literal literal(ShapeUtil::MakeTupleShapeWithPtrs(element_shapes), /*allocate_arrays=*/false); for (int i = 0, end = elements.size(); i < end; ++i) { TF_CHECK_OK( literal.MoveFrom(std::move(elements[i]), /*dest_shape_index=*/{i})); } return literal; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualDynamicSize( const LiteralBase::Piece& other) const { DCHECK(ShapeUtil::Compatible(subshape(), other.subshape())); if (subshape().is_static()) { return true; } for (int64_t i = 0; i < subshape().rank(); ++i) { if (GetDynamicSize(i) != other.GetDynamicSize(i)) { return false; } } return true; } bool LiteralBase::Piece::EqualElements(const LiteralBase::Piece& other) const { if (subshape().is_static() && ShapeUtil::Equal(subshape(), other.subshape()) && subshape().IsArray()) { CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(size_bytes_dense(), other.size_bytes_dense()); if (primitive_util::IsSubByteNonPredType(subshape().element_type())) { CHECK(!primitive_util::IsFloatingPointType(subshape().element_type())); auto one_array = buffer(); auto two_array = other.buffer(); const int bits_per_element = primitive_util::BitWidth(subshape().element_type()); const uint8_t mask = LsbMask<uint8_t>(bits_per_element); for (int64_t i = 0; i < size_bytes_dense(); ++i) { if ((one_array[i] & mask) != (two_array[i] & mask)) return false; } return true; } return memcmp(buffer(), other.buffer(), size_bytes_dense()) == 0; } std::vector<int64_t> multi_index; return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeSrcT = NativeTypeOf<primitive_type_constant>; return EqualElementsInternal<NativeSrcT>(other, &multi_index); }, subshape().element_type()); } bool LiteralBase::Equal(const LiteralBase& other, bool layout_sensitive) const { // Checking the structure of tuple literals. Checks for dense arrays are // performed below. if (!ShapeUtil::EqualStructure(shape(), other.shape())) { return false; } return root_piece().ForEachSubpieceWithBool([&](const ShapeIndex& index, const Piece& piece) { const Piece& other_piece = other.piece(index); const Shape& subshape = piece.subshape(); const Shape& other_subshape = other_piece.subshape(); if (subshape.element_type() != other_subshape.element_type()) { return false; } if (!piece.subshape().IsArray()) { return true; } if (subshape.rank() != other_subshape.rank()) { return false; } if (layout_sensitive && (subshape.layout() != other_subshape.layout())) { return false; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (piece.GetDynamicSize(i) != other_piece.GetDynamicSize(i)) { return false; } } if (!piece.EqualElements(other_piece)) { return false; } return true; }); } return root_piece().ForEachSubpieceWithBool([&](const ShapeIndex& index, const Piece& piece) { const Piece& other_piece = other.piece(index); const Shape& subshape = piece.subshape(); const Shape& other_subshape = other_piece.subshape(); if (subshape.element_type() != other_subshape.element_type()) { return false; } if (!piece.subshape().IsArray()) { return true; } if (subshape.rank() != other_subshape.rank()) { return false; } if (layout_sensitive && (subshape.layout() != other_subshape.layout())) { return false; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (piece.GetDynamicSize(i) != other_piece.GetDynamicSize(i)) { return false; } } if (!piece.EqualElements(other_piece)) { return false; } return true; }); static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(std::complex<T> a, std::complex<T> b) { return EqualIncludingNan(a.real(), b.real()) && EqualIncludingNan(a.imag(), b.imag()); } static bool EqualIncludingNan(std::complex<T> a, std::complex<T> b) { return EqualIncludingNan(a.real(), b.real()) && EqualIncludingNan(a.imag(), b.imag()); } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } bool Literal::Piece::IsAll(const Literal& scalar) const { CHECK(ShapeUtil::IsScalar(scalar.shape())) << scalar.shape().ToString(); if (!subshape().IsArray()) { return false; } CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(subshape().element_type(), scalar.shape().element_type()); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, subshape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, int64_t Literal::Piece::CountAll(const Literal& scalar) const { CHECK(ShapeUtil::IsScalar(scalar.shape())) << scalar.shape().ToString(); if (!subshape().IsArray()) { return 0; } CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(subshape().element_type(), scalar.shape().element_type()); return primitive_util::ArrayTypeSwitch<int64_t>( [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, subshape().element_type()); } [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { bool LiteralBase::IsAll(const Literal& scalar) const { return root_piece().IsAll(scalar); } bool LiteralBase::IsAll(int8_t value) const { if (!shape().IsArray()) { return false; } PrimitiveType ty = shape().element_type(); if (primitive_util::IsFloatingPointType(ty)) { return IsAllFloatImpl(value, /*round_value=*/false); } if (primitive_util::IsUnsignedIntegralType(ty) && value < 0) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllFloat(float value) const { return IsAllFloatImpl(value, /*round_value=*/true); } bool LiteralBase::IsAllFloatImpl(float value, bool round_value) const { PrimitiveType ty = shape().element_type(); if (!primitive_util::IsFloatingPointType(ty)) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::FloatingPointTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllComplex(complex64 value) const { PrimitiveType ty = shape().element_type(); if (!primitive_util::IsComplexType(ty)) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::ComplexTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllFirst() const { if (!shape().IsArray()) { return false; } // Empty shapes are not all the first element since there is no first element. if (ShapeUtil::IsZeroElementArray(shape())) { return false; } absl::InlinedVector<int64_t, 4> start_indices(/*n=*/shape().rank(), 0); absl::InlinedVector<int64_t, 4> end_indices(/*n=*/shape().rank(), 1); Literal first = Slice(start_indices, end_indices); return IsAll(first.Reshape({}).value()); } bool LiteralBase::IsR1Iota() const { if (!shape().IsArray()) { return false; } CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); if (shape().rank() != 1) { return false; } return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, shape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, std::optional<int64_t> LiteralBase::IsR1StridedIota() const { if (!shape().IsArray() || shape().rank() != 1) { return std::nullopt; } CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); const int64_t elements = ShapeUtil::ElementsIn(shape()); const PrimitiveType type = shape().element_type(); if (elements <= 1 || !primitive_util::IsIntegralType(type)) { return std::nullopt; } return primitive_util::IntegralTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, bool LiteralBase::IsZero(absl::Span<const int64_t> indices) const { CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, shape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void LiteralBase::Piece::set_array_value_state(ArrayValueState state) { array_value_state_ = state; } LiteralBase::ArrayValueState LiteralBase::Piece::get_array_value_state() const { return array_value_state_; } void LiteralBase::Piece::WriteToProto(LiteralProto* proto) const { *proto->mutable_shape() = subshape().ToProto(); switch (subshape().element_type()) { case PRED: CopyToRepeatedField(proto->mutable_preds(), data<bool>()); break; case U2: *proto->mutable_u2s() = std::string( reinterpret_cast<const char*>(data<u2>().data()), size_bytes_dense()); break; case U4: *proto->mutable_u4s() = std::string( reinterpret_cast<const char*>(data<u4>().data()), size_bytes_dense()); break; case U8: proto->set_u8s(static_cast<const unsigned char*>(data<uint8_t>().data()), element_count()); break; case U16: *proto->mutable_u16s() = std::string(reinterpret_cast<const char*>(data<uint16_t>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_u16s()); } break; case U32: CopyToRepeatedField(proto->mutable_u32s(), data<uint32_t>()); break; case U64: CopyToRepeatedField(proto->mutable_u64s(), data<uint64_t>()); break; case S2: *proto->mutable_s2s() = std::string( reinterpret_cast<const char*>(data<s2>().data()), size_bytes_dense()); break; case S4: *proto->mutable_s4s() = std::string( reinterpret_cast<const char*>(data<s4>().data()), size_bytes_dense()); break; case S8: proto->set_s8s(static_cast<const signed char*>(data<int8_t>().data()), element_count()); break; case S16: *proto->mutable_s16s() = std::string(reinterpret_cast<const char*>(data<int16_t>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_s16s()); } break; case S32: CopyToRepeatedField(proto->mutable_s32s(), data<int32_t>()); break; case S64: CopyToRepeatedField(proto->mutable_s64s(), data<int64_t>()); break; case F8E5M2: *proto->mutable_f8e5m2s() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e5m2>().data()), size_bytes_dense()); break; case F8E4M3FN: *proto->mutable_f8e4m3fns() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3fn>().data()), size_bytes_dense()); break; case F8E4M3B11FNUZ: *proto->mutable_f8e4m3b11fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3b11fnuz>().data()), size_bytes_dense()); break; case F8E5M2FNUZ: *proto->mutable_f8e5m2fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e5m2fnuz>().data()), size_bytes_dense()); break; case F8E4M3FNUZ: *proto->mutable_f8e4m3fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3fnuz>().data()), size_bytes_dense()); break; case F16: *proto->mutable_f16s() = std::string(reinterpret_cast<const char*>(data<half>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_f16s()); } break; case BF16: *proto->mutable_bf16s() = std::string(reinterpret_cast<const char*>(data<bfloat16>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_bf16s()); } break; case F32: CopyToRepeatedField(proto->mutable_f32s(), data<float>()); break; case F64: CopyToRepeatedField(proto->mutable_f64s(), data<double>()); break; case C64: for (complex64 value : data<complex64>()) { proto->add_c64s(value.real()); proto->add_c64s(value.imag()); } break; case C128: for (complex128 value : data<complex128>()) { proto->add_c128s(value.real()); proto->add_c128s(value.imag()); } break; case TUPLE: case TOKEN: // Nothing to do but assign the shape which is done above. return; default: // TODO(b/111551621): Support serializing more PrimitiveTypes. LOG(FATAL) << "Unhandled primitive type " << PrimitiveType_Name(subshape().element_type()); } } const void* LiteralBase::Piece::untyped_data() const { DCHECK(LayoutUtil::IsDenseArray(subshape())) << ShapeUtil::HumanString(subshape()); return buffer(); } void* LiteralBase::Piece::untyped_data() { DCHECK(LayoutUtil::IsDenseArray(subshape())) << ShapeUtil::HumanString(subshape()); return buffer(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status LiteralBase::Piece::CopyFromProto(const LiteralProto& proto) { // These conditions should have been checked in // MutableLiteralBase::CreateFromProto. TF_RET_CHECK(proto.has_shape()); Shape shape(proto.shape()); TF_RET_CHECK(LayoutUtil::HasLayout(shape)); TF_RET_CHECK(ShapeUtil::Equal(shape, subshape())); switch (subshape().element_type()) { case PRED: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<bool>(), proto.preds())); break; case S2: { const std::string& s(proto.s2s()); TF_RET_CHECK(data<s2>().size() * sizeof(s2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case S4: { const std::string& s(proto.s4s()); TF_RET_CHECK(data<s4>().size() * sizeof(s4) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case S8: { auto s8_data = data<int8_t>(); TF_RET_CHECK(proto.s8s().size() == s8_data.size()); std::copy(proto.s8s().begin(), proto.s8s().end(), s8_data.begin()); break; } case S16: { const std::string& s(proto.s16s()); TF_RET_CHECK(data<int16_t>().size() * sizeof(int16_t) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case S32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<int32_t>(), proto.s32s())); break; case S64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<int64_t>(), proto.s64s())); break; case U2: { const std::string& s(proto.u2s()); TF_RET_CHECK(data<u2>().size() * sizeof(u2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case U4: { const std::string& s(proto.u4s()); TF_RET_CHECK(data<u4>().size() * sizeof(u4) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case U8: { auto u8_data = data<uint8_t>(); TF_RET_CHECK(proto.u8s().size() == u8_data.size()); std::copy(proto.u8s().begin(), proto.u8s().end(), u8_data.begin()); break; } case U16: { const std::string& s(proto.u16s()); TF_RET_CHECK(data<uint16_t>().size() * sizeof(uint16_t) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case U32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<uint32_t>(), proto.u32s())); break; case U64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<uint64_t>(), proto.u64s())); break; case F8E5M2: { const std::string& s(proto.f8e5m2s()); TF_RET_CHECK(data<tsl::float8_e5m2>().size() * sizeof(tsl::float8_e5m2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3FN: { const std::string& s(proto.f8e4m3fns()); TF_RET_CHECK(data<tsl::float8_e4m3fn>().size() * sizeof(tsl::float8_e4m3fn) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3B11FNUZ: { const std::string& s(proto.f8e4m3b11fnuzs()); TF_RET_CHECK(data<tsl::float8_e4m3b11fnuz>().size() * sizeof(tsl::float8_e4m3b11fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E5M2FNUZ: { const std::string& s(proto.f8e5m2fnuzs()); TF_RET_CHECK(data<tsl::float8_e5m2fnuz>().size() * sizeof(tsl::float8_e5m2fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3FNUZ: { const std::string& s(proto.f8e4m3fnuzs()); TF_RET_CHECK(data<tsl::float8_e4m3fnuz>().size() * sizeof(tsl::float8_e4m3fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F16: { const std::string& s(proto.f16s()); TF_RET_CHECK(data<half>().size() * sizeof(half) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case BF16: { const std::string& s(proto.bf16s()); TF_RET_CHECK(data<bfloat16>().size() * sizeof(bfloat16) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case F32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<float>(), proto.f32s())); break; case F64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<double>(), proto.f64s())); break; case C64: { auto complex_data = data<complex64>(); TF_RET_CHECK(proto.c64s_size() == complex_data.size() * 2); for (int64_t i = 0; i < complex_data.size(); ++i) { complex_data[i] = complex64{proto.c64s(i * 2), proto.c64s(i * 2 + 1)}; } break; } case C128: { auto complex_data = data<complex128>(); const int64_t complex_data_size_doubled = complex_data.size() * 2; TF_RET_CHECK(proto.c128s_size() == complex_data_size_doubled); for (int64_t i = 0, end = complex_data.size(); i < end; ++i) { complex_data[i] = complex128{proto.c128s(i * 2), proto.c128s(i * 2 + 1)}; } break; } case TUPLE: return InvalidArgument("Should not be called on tuple shapes: %s", ShapeUtil::HumanString(subshape())); default: return InvalidArgument("Is called on unsupported shape: %s", ShapeUtil::HumanString(subshape())); } return absl::OkStatus(); } bool LiteralBase::Piece::IsKnown() const { if (array_value_state_ != ArrayValueState::kKnown) { return false; } if (subshape().IsTuple()) { bool are_all_leaf_arrays_known = true; ForEachSubpiece([&are_all_leaf_arrays_known](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_known &= piece.IsKnown(); }); return are_all_leaf_arrays_known; } return true; } ForEachSubpiece([&are_all_leaf_arrays_known](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_known &= piece.IsKnown(); }); bool LiteralBase::Piece::IsDetermined() const { if (array_value_state_ == ArrayValueState::kUndetermined) { return false; } if (subshape().IsTuple()) { bool are_all_leaf_arrays_determined = true; ForEachSubpiece([&are_all_leaf_arrays_determined](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_determined &= piece.IsDetermined(); }); return are_all_leaf_arrays_determined; } return true; } ForEachSubpiece([&are_all_leaf_arrays_determined](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_determined &= piece.IsDetermined(); }); LiteralProto LiteralBase::ToProto() const { LiteralProto proto; root_piece().ForEachSubpiece( [&](const ShapeIndex& index, const Piece& piece) { LiteralProto* proto_piece = &proto; for (int64_t i : index) { while (proto_piece->tuple_literals_size() <= i) { proto_piece->add_tuple_literals(); } proto_piece = proto_piece->mutable_tuple_literals(i); } piece.WriteToProto(proto_piece); }); return proto; } [&](const ShapeIndex& index, const Piece& piece) { LiteralProto* proto_piece = &proto; for (int64_t i : index) { while (proto_piece->tuple_literals_size() <= i) { proto_piece->add_tuple_literals(); } proto_piece = proto_piece->mutable_tuple_literals(i); } piece.WriteToProto(proto_piece); }); const void* LiteralBase::untyped_data(const ShapeIndex& shape_index) const { return piece(shape_index).untyped_data(); } void* MutableLiteralBase::untyped_data(const ShapeIndex& shape_index) { return piece(shape_index).untyped_data(); } int64_t LiteralBase::size_bytes(const ShapeIndex& shape_index) const { return piece(shape_index).size_bytes_dense(); } std::string LiteralBase::GetR1U8AsString() const { CHECK(shape().IsArray()); CHECK_EQ(shape().rank(), 1); CHECK_EQ(shape().element_type(), U8); return std::string(absl::bit_cast<const char*>(data<uint8_t>().data()), ShapeUtil::ElementsIn(shape())); } void MutableBorrowingLiteral::CopyPieceSubtree(const Shape& shape, const Piece* src_piece, Piece* dest_piece) { DCHECK(ShapeUtil::Equal(src_piece->subshape(), dest_piece->subshape())) << "src_piece has shape: " << ShapeUtil::HumanString(src_piece->subshape()) << "dest_piece has shape: " << ShapeUtil::HumanString(dest_piece->subshape()); dest_piece->set_array_value_state(src_piece->get_array_value_state()); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); Piece child_piece; child_piece.set_subshape(&subshape); CopyPieceSubtree(subshape, &src_piece->child(i), &child_piece); dest_piece->emplace_back(std::move(child_piece)); } } else if (shape.IsArray()) { dest_piece->set_buffer(const_cast<char*>(src_piece->buffer())); } } MutableLiteralBase::~MutableLiteralBase() = default; MutableBorrowingLiteral::MutableBorrowingLiteral( const MutableBorrowingLiteral& literal) : MutableLiteralBase() { shape_ = literal.shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.root_piece(), root_piece_); } MutableBorrowingLiteral& MutableBorrowingLiteral::operator=( const MutableBorrowingLiteral& literal) { shape_ = literal.shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.root_piece(), root_piece_); return *this; } MutableBorrowingLiteral::MutableBorrowingLiteral(MutableLiteralBase* literal) : MutableLiteralBase() { shape_ = literal->shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal->root_piece(), root_piece_); } MutableBorrowingLiteral::MutableBorrowingLiteral( MutableBorrowingLiteral literal, const ShapeIndex& view_root) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(literal.piece(view_root).subshape()); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.piece(view_root), root_piece_); } MutableBorrowingLiteral::MutableBorrowingLiteral(const char* src_buf_ptr, const Shape& shape) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(shape); CHECK(LayoutUtil::HasLayout(*shape_)); CHECK(!shape_->IsTuple()); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); root_piece_->set_buffer(const_cast<char*>(src_buf_ptr)); } MutableBorrowingLiteral::MutableBorrowingLiteral(absl::Span<char*> src_buf_ptrs, const Shape& shape) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(shape); if (!shape_->IsTuple()) { CHECK_EQ(src_buf_ptrs.size(), 1); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); root_piece_->set_buffer(const_cast<char*>(src_buf_ptrs[0])); } else { CHECK(!ShapeUtil::IsNestedTuple(*shape_)); CHECK_EQ(src_buf_ptrs.size(), ShapeUtil::TupleElementCount(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); for (int i = 0; i < src_buf_ptrs.size(); ++i) { Piece child_piece; const auto& src_shape = shape_->tuple_shapes(i); CHECK(src_shape.IsArray()); child_piece.set_subshape(&src_shape); child_piece.set_buffer(src_buf_ptrs[i]); root_piece_->emplace_back(std::move(child_piece)); } } } MutableBorrowingLiteral::MutableBorrowingLiteral(ShapeTree<char*> src_buf_ptrs) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(src_buf_ptrs.shape()); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); BuildPieceSubtree(*shape_, root_piece_); root_piece_->ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); } [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); MutableBorrowingLiteral::~MutableBorrowingLiteral() { if (root_piece_ != nullptr) { delete root_piece_; } } LiteralSlice::LiteralSlice(const LiteralBase& literal) : LiteralBase(), root_piece_(&literal.root_piece()) {} LiteralSlice::LiteralSlice(const LiteralBase& literal, const ShapeIndex& view_root) : LiteralBase(), root_piece_(&literal.piece(view_root)) {} BorrowingLiteral::BorrowingLiteral(const char* src_buf_ptr, const Shape& shape) : LiteralBase(), shape_(std::make_unique<Shape>(shape)) { CHECK(shape_->IsArray()); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); root_piece_.set_buffer(const_cast<char*>(src_buf_ptr)); } BorrowingLiteral::BorrowingLiteral(absl::Span<const char* const> src_buf_ptrs, const Shape& shape) : LiteralBase(), shape_(std::make_unique<Shape>(shape)) { CHECK(shape_->IsTuple()); CHECK(!ShapeUtil::IsNestedTuple(*shape_)); CHECK_EQ(src_buf_ptrs.size(), ShapeUtil::TupleElementCount(*shape_)); root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); BuildPieceSubtree(*shape_, &root_piece_); for (int i = 0, end = src_buf_ptrs.size(); i < end; ++i) { const auto& src_shape = shape_->tuple_shapes(i); CHECK(src_shape.IsArray()); root_piece_.child(i).set_buffer(const_cast<char*>(src_buf_ptrs[i])); } } BorrowingLiteral::BorrowingLiteral(ShapeTree<const char*> src_buf_ptrs) : LiteralBase(), shape_(std::make_unique<Shape>(src_buf_ptrs.shape())) { root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); BuildPieceSubtree(*shape_, &root_piece_); root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); } [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); });
#include "xla/literal.h" #include <algorithm> #include <cmath> #include <complex> #include <cstdint> #include <functional> #include <limits> #include <random> #include <string> #include <tuple> #include <utility> #include <vector> #include "absl/base/casts.h" #include "absl/hash/hash.h" #include "absl/random/random.h" #include "absl/status/status.h" #include "absl/strings/match.h" #include "absl/types/span.h" #include "xla/array.h" #include "xla/array2d.h" #include "xla/array3d.h" #include "xla/array4d.h" #include "xla/index_util.h" #include "xla/layout.h" #include "xla/layout_util.h" #include "xla/literal_util.h" #include "xla/primitive_util.h" #include "xla/shape.h" #include "xla/shape_tree.h" #include "xla/shape_util.h" #include "xla/test.h" #include "xla/types.h" #include "xla/util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/errors.h" #include "tsl/platform/logging.h" // IWYU pragma: keep #include "tsl/platform/macros.h" #include "tsl/platform/ml_dtypes.h" #include "tsl/platform/statusor.h" #include "tsl/platform/test_benchmark.h" class LiteralUtilTest : public ::testing::Test { protected: LiteralUtilTest() { Array4D<float> arr4d({ // clang-format off { // i0=0 { // i1=0 {1, 2, 3}, // i2=0 {4, 5, 6}, // i2=1 {7, 8, 9}, // i2=2 }, { // i1=1 {11, 12, 13}, {14, 15, 16}, {17, 18, 19}, }, }, { // i0=1 { // i1=0 {101, 102, 103}, {104, 105, 106}, {107, 108, 109}, }, { // i1=1 {201, 202, 203}, // i2=0 {204, 205, 206}, // i2=1 {207, 208, 209}, // i2=2 }, }, // clang-format on }); layout_r2_dim0major_ = LayoutUtil::MakeLayout({1, 0}); layout_r2_dim0minor_ = LayoutUtil::MakeLayout({0, 1}); layout_r3_dim0major_ = LayoutUtil::MakeLayout({2, 1, 0}); layout_r3_dim0minor_ = LayoutUtil::MakeLayout({0, 1, 2}); layout_r4_dim0major_ = LayoutUtil::MakeLayout({3, 2, 1, 0}); layout_r4_dim0minor_ = LayoutUtil::MakeLayout({0, 1, 2, 3}); literal_r4_2x2x3x3_dim0major_ = LiteralUtil::CreateR4FromArray4DWithLayout<float>(arr4d, layout_r4_dim0major_); literal_r4_2x2x3x3_dim0minor_ = LiteralUtil::CreateR4FromArray4DWithLayout<float>(arr4d, layout_r4_dim0minor_); } Layout layout_r2_dim0major_; Layout layout_r2_dim0minor_; Layout layout_r3_dim0major_; Layout layout_r3_dim0minor_; Layout layout_r4_dim0major_; Layout layout_r4_dim0minor_; Literal literal_r4_2x2x3x3_dim0major_; Literal literal_r4_2x2x3x3_dim0minor_; };
LiteralUtilTest_ConvertIfTypesMatchF8
xla/literal_test.cc
bool LiteralProtoHasValues(const LiteralProto& proto) { return !proto.s2s().empty() || !proto.s4s().empty() || !proto.s8s().empty() || !proto.s16s().empty() || proto.s32s_size() || proto.s64s_size() || !proto.u2s().empty() || !proto.u4s().empty() || !proto.u8s().empty() || !proto.u16s().empty() || proto.u32s_size() || proto.u64s_size() || !proto.f8e5m2s().empty() || !proto.f8e4m3fns().empty() || !proto.f8e4m3b11fnuzs().empty() || !proto.f8e5m2fnuzs().empty() || !proto.f8e4m3fnuzs().empty() || !proto.f16s().empty() || !proto.bf16s().empty() || proto.f32s_size() || proto.f64s_size() || proto.c64s_size() || proto.c128s_size() || proto.preds_size() || proto.tuple_literals_size(); } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { const Shape& NilShape() { static const Shape* shape = new Shape(TUPLE, {}, {}, {}); return *shape; } const Shape* TryInternShape(const Shape& shape) { if (shape.IsTuple() && shape.tuple_shapes_size() == 0) { return &NilShape(); } if (shape.IsArray() && shape.dimensions_size() == 0 && shape.is_static() && shape.layout().tiles_size() == 0 && shape.layout().memory_space() == 0) { return &ScalarShape(shape.element_type()); } return nullptr; } StrideConfig::StrideConfig(const Shape& source_shape, const Shape& dest_shape, absl::Span<const int64_t> dimensions) : dimensions(dimensions), base(dimensions.size(), 0), step(dimensions.size(), 1) { if (!dimensions.empty()) { // Selects the shape with the largest minor dimension as the one upon // which to run the tight stride loop. if (dimensions[LayoutUtil::Minor(source_shape.layout(), 0)] >= dimensions[LayoutUtil::Minor(dest_shape.layout(), 0)]) { minor_dimension = LayoutUtil::Minor(source_shape.layout(), 0); dest_stride = IndexUtil::GetDimensionStride(dest_shape, minor_dimension); } else { minor_dimension = LayoutUtil::Minor(dest_shape.layout(), 0); source_stride = IndexUtil::GetDimensionStride(source_shape, minor_dimension); } minor_loop_size = dimensions[minor_dimension]; step[minor_dimension] = minor_loop_size; } } LiteralBase::~LiteralBase() = default; const Shape& LiteralBase::shape() const { return root_piece().subshape(); } const char* LiteralBase::Piece::buffer() const { // std::visit is avoided here due to its code size issues. if (auto* r = std::get_if<DenseRep>(&rep_)) { return r->data; } if (auto* r = std::get_if<DenseInlinedRep>(&rep_)) { return r->data; } DCHECK(std::holds_alternative<TupleRep>(rep_) || std::holds_alternative<Uninitialized>(rep_)); return nullptr; } const LiteralBase::Piece& LiteralBase::piece( const ShapeIndex& shape_index) const { const Piece* piece = &root_piece(); for (const auto i : shape_index) { DCHECK_GE(i, 0); DCHECK_LT(i, piece->children_size()); piece = &piece->child(i); } return *piece; } std::ostream& operator<<(std::ostream& out, const Literal& literal) { out << literal.ToString(); return out; } Shape* MutableLiteralBase::mutable_shape_do_not_use() { const Shape* const_shape = shape_.get(); if (!shape_.OwnsPtr()) { shape_ = MaybeOwningShapePtr(std::make_unique<Shape>(*shape_)); } Shape* shape = shape_.get_mutable(); if (shape != const_shape) { std::function<void(const Shape&, Piece*)> set_piece_shapes = [&set_piece_shapes](const Shape& shape, Piece* piece) { piece->set_subshape(&shape); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); set_piece_shapes(subshape, &piece->child(i)); } } }; set_piece_shapes(*shape, &mutable_root_piece()); } return shape; } [&set_piece_shapes](const Shape& shape, Piece* piece) { piece->set_subshape(&shape); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); set_piece_shapes(subshape, &piece->child(i)); } } }; Literal::Literal() : Literal(NilShape()) {} Literal::Literal(const Shape& shape) : Literal(shape, /*allocate_arrays=*/true) {} void Literal::SetShape(const Shape& shape) { Shape shape_storage; const Shape* shape_ptr = &shape; if (LayoutUtil::HasCustomElementSizeInBits(shape)) { shape_storage = shape; shape_storage.mutable_layout()->set_element_size_in_bits(0); shape_ptr = &shape_storage; } if (const Shape* intered_shape_ptr = TryInternShape(*shape_ptr)) { shape_ = intered_shape_ptr; } else { shape_ = std::make_unique<Shape>(*shape_ptr); } } void Literal::SetPiece(const Shape& shape, Piece* piece, bool allocate_arrays, ArrayValueState leaf_array_value_state) { if (shape.IsTuple()) { for (const Shape& subshape : shape.tuple_shapes()) { Piece child_piece; child_piece.set_subshape(&subshape); SetPiece(subshape, &child_piece, allocate_arrays, leaf_array_value_state); piece->emplace_back(std::move(child_piece)); } } else if (shape.IsArray()) { DCHECK(LayoutUtil::IsDenseArray(shape)) << "literal array storage is currently only supported for dense " "arrays: " << shape; piece->set_array_value_state(leaf_array_value_state); if (leaf_array_value_state == LiteralBase::ArrayValueState::kKnown && allocate_arrays) { piece->AllocateBuffers(); } } } Literal::Literal(const Shape& shape, bool allocate_arrays, ArrayValueState leaf_array_value_state) : MutableLiteralBase() { SetShape(shape); CHECK(leaf_array_value_state != ArrayValueState::kKnown || LayoutUtil::HasLayout(*shape_)); root_piece_.set_subshape(shape_.get()); CHECK(&root_piece_.subshape() == shape_.get()); SetPiece(*shape_, &root_piece_, allocate_arrays, leaf_array_value_state); } Literal::~Literal() { DeallocateBuffers(); } void Literal::DeallocateBuffers() { root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { piece->DeallocateBuffers(); }); } Literal::Literal(Literal&& other) : MutableLiteralBase() { *this = std::move(other); } Literal& Literal::operator=(Literal&& other) { DCHECK(&other.root_piece_.subshape() == other.shape_.get()); using std::swap; swap(shape_, other.shape_); swap(root_piece_, other.root_piece_); DCHECK(&root_piece_.subshape() == shape_.get()); return *this; } Literal LiteralBase::CreateFromShape(const Shape& shape) { Literal literal(shape); literal.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (piece->subshape().IsArray()) { memset(piece->untyped_data(), 0, piece->size_bytes_dense()); } }); return literal; } [&](const ShapeIndex& index, Piece* piece) { if (piece->subshape().IsArray()) { memset(piece->untyped_data(), 0, piece->size_bytes_dense()); } }); Literal LiteralBase::CreateFromShapeWithUnknownLeafArrays(const Shape& shape) { Literal literal(shape, /*allocate_arrays=*/false, ArrayValueState::kUnknown); return literal; } Literal LiteralBase::CreateFromShapeWithUndeterminedLeafArrays( const Shape& shape) { Literal literal(shape, /*allocate_arrays=*/false, ArrayValueState::kUndetermined); return literal; } int32_t LiteralBase::GetDynamicSize(int64_t dim_index) const { return GetDynamicSize(dim_index, {}); } int32_t LiteralBase::GetDynamicSize(int64_t dim_index, const ShapeIndex& shape_index) const { return piece(shape_index).GetDynamicSize(dim_index); } std::optional<int64_t> LiteralBase::GetFirstInteger() const { if (!primitive_util::IsIntegralType(shape().element_type())) { return std::nullopt; } return primitive_util::IntegralTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, void LiteralBase::BuildPieceSubtree(const Shape& shape, Piece* piece) { CHECK(shape.IsTuple()); for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); Piece child_piece; child_piece.set_subshape(&subshape); if (subshape.IsTuple()) { BuildPieceSubtree(subshape, &child_piece); } piece->emplace_back(std::move(child_piece)); } } absl::Status LiteralBase::SerializeToString(std::string* output) const { ShapeProto shape_proto = shape().ToProto(); TF_ASSIGN_OR_RETURN(int64_t size, ShapeUtil::SerializedSizeWithProto(shape(), shape_proto)); output->resize(size); return SerializeWithShapeProto(shape_proto, output->data()); } absl::StatusOr<std::string> LiteralBase::SerializeAsString() const { std::string result; TF_RETURN_IF_ERROR(SerializeToString(&result)); return std::move(result); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { void MutableLiteralBase::CopyElementFrom(const LiteralSlice& src_literal, absl::Span<const int64_t> src_index, absl::Span<const int64_t> dest_index) { DCHECK(LayoutUtil::IsDenseArray(shape())); DCHECK_EQ(shape().element_type(), src_literal.shape().element_type()); const int64_t src_linear_index = IndexUtil::MultidimensionalIndexToLinearIndex(src_literal.shape(), src_index); const int64_t dest_linear_index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), dest_index); const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); char* dest_address = static_cast<char*>(untyped_data()) + dest_linear_index * primitive_size; const char* source_address = static_cast<const char*>(src_literal.untyped_data()) + src_linear_index * primitive_size; if (dest_address != source_address) { memcpy(dest_address, source_address, primitive_size); } } /* static */ absl::StatusOr<Literal> MutableLiteralBase::CreateFromProto( const LiteralProto& proto, bool prohibit_empty_literal) { if (!proto.has_shape()) { return InvalidArgument("LiteralProto has no shape"); } Shape shape(proto.shape()); if (ShapeUtil::HasPrimitiveType(shape, OPAQUE_TYPE)) { return InvalidArgument( "Literal shape cannot include OPAQUE_TYPE sub-shape"); } if (!LayoutUtil::HasLayout(shape)) { return InvalidArgument("LiteralProto has no layout"); } if (LayoutUtil::IsSparseArray(shape)) { return Unimplemented("Sparse literals are not supported"); } TF_RETURN_IF_ERROR(ShapeUtil::ValidateShapeWithOptionalLayout(shape)); Literal literal(shape); TF_RETURN_IF_ERROR(literal.root_piece_.ForEachMutableSubpieceWithStatus( [&](const ShapeIndex& index, Piece* piece) -> absl::Status { const LiteralProto* proto_element = &proto; for (int64_t i : index) { CHECK(i < proto_element->tuple_literals_size()); proto_element = &proto_element->tuple_literals(i); } if (piece->subshape().IsTuple()) { if (proto_element->tuple_literals_size() != ShapeUtil::TupleElementCount(piece->subshape())) { return InvalidArgument( "Expected %d tuple elements in LiteralProto, has %d", ShapeUtil::TupleElementCount(piece->subshape()), proto_element->tuple_literals_size()); } return absl::OkStatus(); } if (piece->subshape().element_type() == TOKEN) { return absl::OkStatus(); } CHECK(piece->subshape().IsArray()); // When prohibit_empty_literal is false (allowing literal with no // values), only copy from proto if the literal proto has values. This // mode is used for a learned cost model. if (prohibit_empty_literal || LiteralProtoHasValues(*proto_element)) { TF_RETURN_IF_ERROR(piece->CopyFromProto(*proto_element)); } return absl::OkStatus(); })); return std::move(literal); } TF_RETURN_IF_ERROR(literal.root_piece_.ForEachMutableSubpieceWithStatus( Literal Literal::SubLiteral(ShapeIndexView shape_index) { if (!shape_index.empty()) { auto decomposed = this->DecomposeTuple(); return decomposed.at(shape_index.front()) .SubLiteral(shape_index.subspan(1)); } else { return std::move(*this); } } std::vector<Literal> Literal::DecomposeTuple() { CHECK(shape().IsTuple()); std::vector<Literal> elements; const auto tuple_element_count = ShapeUtil::TupleElementCount(shape()); elements.reserve(tuple_element_count); for (int i = 0; i < tuple_element_count; ++i) { elements.push_back(Literal(ShapeUtil::GetSubshape(shape(), {i}), /*allocate_arrays=*/false)); Literal& element = elements.back(); element.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* dest_piece) { if (dest_piece->subshape().IsTuple()) { return; } ShapeIndex src_index = {i}; for (int64_t j : index) { src_index.push_back(j); } Piece& src_piece = piece(src_index); // Move the respective buffer over to the element Literal. dest_piece->MoveDataFrom(src_piece); }); } // Set this literal to be nil-shaped. *this = Literal(); return elements; } [&](const ShapeIndex& index, Piece* dest_piece) { if (dest_piece->subshape().IsTuple()) { return; } ShapeIndex src_index = {i}; for (int64_t j : index) { src_index.push_back(j); } Piece& src_piece = piece(src_index); // Move the respective buffer over to the element Literal. dest_piece->MoveDataFrom(src_piece); }); void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } int32_t LiteralBase::Piece::GetDynamicSize(int64_t dim_index) const { CHECK(LayoutUtil::IsDenseArray(subshape())); if (!subshape_->is_dynamic_dimension(dim_index)) { // This is a static dimension, return size. return subshape_->dimensions(dim_index); } return dynamic_size_buffer()[dim_index]; } void LiteralBase::Piece::SetDynamicSize(int64_t dim_index, int32_t size) { CHECK(LayoutUtil::IsDenseArray(subshape())); CHECK(subshape_->is_dynamic_dimension(dim_index)); dynamic_size_buffer()[dim_index] = size; } void LiteralBase::Piece::AllocateBuffers() { const int64_t bytes = total_bytes_dense(); if (bytes > kMaxInlinedBytes) { CHECK_EQ(buffer(), nullptr); rep_.emplace<DenseRep>(); set_buffer( static_cast<char*>(tsl::port::AlignedMalloc(bytes, kMinimumAlignment))); } else { rep_.emplace<DenseInlinedRep>(); } } void LiteralBase::Piece::DeallocateBuffers() { if (auto* array_rep = GetDenseRep()) { tsl::port::AlignedFree(array_rep->data); rep_.emplace<Uninitialized>(); } } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } absl::Status LiteralBase::Piece::CopyFrom(const LiteralBase::Piece& src, bool only_dynamic_bound) { CHECK(subshape_ != nullptr); CHECK(src.subshape_ != nullptr); CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK(LayoutUtil::IsDenseArray(src.subshape())) << __func__ << " is only supported for dense arrays: " << src.subshape(); if (!only_dynamic_bound) { CHECK(ShapeUtil::Compatible(subshape(), src.subshape())); } if (src.array_value_state_ == ArrayValueState::kUnknown || src.array_value_state_ == ArrayValueState::kUndetermined) { if (array_value_state_ == ArrayValueState::kKnown) { DeallocateBuffers(); } array_value_state_ = src.array_value_state_; return absl::OkStatus(); } else { CHECK(src.array_value_state_ == ArrayValueState::kKnown); if (array_value_state_ == ArrayValueState::kUndetermined || array_value_state_ == ArrayValueState::kUnknown) { AllocateBuffers(); } array_value_state_ = src.array_value_state_; } if (ShapeUtil::Equal(subshape(), src.subshape())) { // If the layouts are equal it's faster just to memcpy. memcpy(buffer(), src.buffer(), src.size_bytes_dense()); } else { std::vector<int64_t> origin(subshape().rank(), 0); primitive_util::ArrayTypeSwitch<void>( [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, subshape().element_type()); } DCHECK_EQ(dynamic_size_buffer_bytes(), src.dynamic_size_buffer_bytes()); if (subshape().is_dynamic() && src.subshape().is_dynamic()) { memcpy(dynamic_size_buffer(), src.dynamic_size_buffer(), src.dynamic_size_buffer_bytes()); } return absl::OkStatus(); } [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, void MutableLiteralBase::SetDynamicSize(int64_t dim_index, int32_t size) { return SetDynamicSize(dim_index, {}, size); } void MutableLiteralBase::SetDynamicSize(int64_t dim_index, const ShapeIndex& shape_index, int32_t size) { Shape* subshape = ShapeUtil::GetMutableSubshape(mutable_shape_do_not_use(), shape_index); CHECK(LayoutUtil::IsDenseArray(*subshape)) << __func__ << " is only supported for dense arrays: " << *subshape; CHECK_GE(subshape->dimensions(dim_index), size); subshape->set_dynamic_dimension(dim_index, true); CHECK_EQ(&piece(shape_index).subshape(), subshape); piece(shape_index).SetDynamicSize(dim_index, size); } absl::Status MutableLiteralBase::CopyFrom(const LiteralSlice& src_literal, const ShapeIndex& dest_shape_index, const ShapeIndex& src_shape_index, bool only_dynamic_bound) { const Shape& dest_subshape = ShapeUtil::GetSubshape(shape(), dest_shape_index); const Shape& src_subshape = ShapeUtil::GetSubshape(src_literal.shape(), src_shape_index); if (only_dynamic_bound) { auto& bound_shape = dest_subshape.is_static() ? src_subshape : dest_subshape; auto& compact_shape = dest_subshape.is_static() ? dest_subshape : src_subshape; CHECK(ShapeUtil::DynamicShapeIsCompatible(compact_shape, bound_shape)) << compact_shape.ToString() << " vs " << bound_shape.ToString(); } else { if (!ShapeUtil::Compatible(dest_subshape, src_subshape)) { return InvalidArgument( "Destination subshape incompatible with source subshape: %s vs %s", ShapeUtil::HumanString(dest_subshape), ShapeUtil::HumanString(src_subshape)); } } return mutable_root_piece().ForEachMutableSubpieceWithStatus( [&](const ShapeIndex& index, Piece* piece) { if (!piece->subshape().IsArray()) { return absl::OkStatus(); } // Determine if this index is in the part of this literal that we want // to copy over from src_literal. bool in_subtree_to_copy = true; for (int i = 0; i < dest_shape_index.size(); ++i) { if (index[i] != dest_shape_index[i]) { in_subtree_to_copy = false; break; } } if (!in_subtree_to_copy) { return absl::OkStatus(); } // Construct the index of the corresponding piece in the source literal. ShapeIndex src_piece_index = src_shape_index; for (int64_t i = dest_shape_index.size(), end = index.size(); i < end; ++i) { src_piece_index.push_back(index[i]); } TF_RETURN_IF_ERROR( piece->CopyFrom(src_literal.piece(src_piece_index), /*only_dynamic_bound=*/only_dynamic_bound)); return absl::OkStatus(); }); } [&](const ShapeIndex& index, Piece* piece) { if (!piece->subshape().IsArray()) { return absl::OkStatus(); } // Determine if this index is in the part of this literal that we want // to copy over from src_literal. bool in_subtree_to_copy = true; for (int i = 0; i < dest_shape_index.size(); ++i) { if (index[i] != dest_shape_index[i]) { in_subtree_to_copy = false; break; } } if (!in_subtree_to_copy) { return absl::OkStatus(); } // Construct the index of the corresponding piece in the source literal. ShapeIndex src_piece_index = src_shape_index; for (int64_t i = dest_shape_index.size(), end = index.size(); i < end; ++i) { src_piece_index.push_back(index[i]); } TF_RETURN_IF_ERROR( piece->CopyFrom(src_literal.piece(src_piece_index), /*only_dynamic_bound=*/only_dynamic_bound)); return absl::OkStatus(); }); absl::Status Literal::MoveFrom(Literal&& src_literal, const ShapeIndex& dest_shape_index) { const Shape& dest_subshape = ShapeUtil::GetSubshape(shape(), dest_shape_index); if (!ShapeUtil::Equal(dest_subshape, src_literal.shape())) { return InvalidArgument( "Destination subshape not equal to source shape: %s vs %s", ShapeUtil::HumanString(dest_subshape), ShapeUtil::HumanString(src_literal.shape())); } src_literal.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& src_index, Piece* src_piece) { if (!src_piece->subshape().IsArray()) { return; } ShapeIndex dest_index = dest_shape_index; for (int64_t i : src_index) { dest_index.push_back(i); } Piece& dest_piece = piece(dest_index); dest_piece.DeallocateBuffers(); dest_piece.MoveDataFrom(*src_piece); }); src_literal.shape_ = MaybeOwningShapePtr(&NilShape()); src_literal.root_piece_ = Piece(); src_literal.root_piece_.set_subshape(src_literal.shape_.get()); return absl::OkStatus(); } [&](const ShapeIndex& src_index, Piece* src_piece) { if (!src_piece->subshape().IsArray()) { return; } ShapeIndex dest_index = dest_shape_index; for (int64_t i : src_index) { dest_index.push_back(i); } Piece& dest_piece = piece(dest_index); dest_piece.DeallocateBuffers(); dest_piece.MoveDataFrom(*src_piece); }); absl::Status MutableLiteralBase::CopySliceFrom( const LiteralSlice& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << shape(); TF_RET_CHECK(LayoutUtil::IsDenseArray(src_literal.shape())) << src_literal.shape(); TF_RET_CHECK(ShapeUtil::SameElementType(src_literal.shape(), shape())); TF_RET_CHECK(src_literal.shape().rank() == src_base.size()); TF_RET_CHECK(shape().rank() == dest_base.size()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, void MutableLiteralBase::PopulateR1(const tsl::core::Bitmap& values) { CHECK(shape().IsArray()); CHECK_EQ(shape().rank(), 1); CHECK_EQ(element_count(), values.bits()); CHECK_EQ(shape().element_type(), PRED); for (int64_t i = 0; i < static_cast<int64_t>(values.bits()); ++i) { Set({i}, values.get(i)); } } void MutableLiteralBase::PopulateInplaceInternal( absl::FunctionRef<void(void*, absl::Span<const int64_t>, int)> populator, bool parallel) { const Shape& this_shape = shape(); const int64_t rank = this_shape.rank(); DCHECK(LayoutUtil::IsDenseArray(this_shape)); char* const dest_base = static_cast<char*>(untyped_data()); if (rank > 0) { StrideConfig stride_config(this_shape, this_shape, this_shape.dimensions()); const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); const int64_t num_elements = ShapeUtil::ElementsIn(shape()); // If we are rank-1 and we are `parallel`, it is better to use a smaller // `step` than what `StrideConfig` does: stick the entire dimension in the // inner-most loop. if (parallel && this_shape.rank() == 1) { const int64_t thread_count = ShapeUtil::GetForEachIndexParallelThreadCount(); // Let's just divide up the array into small amounts per thread. stride_config.dest_stride = stride_config.minor_loop_size = num_elements > 32 ? std::max<int64_t>(num_elements / thread_count, 1) : num_elements; stride_config.step = {stride_config.minor_loop_size}; } auto init_function = [&](absl::Span<const int64_t> indexes, int thread_id) -> absl::StatusOr<bool> { const int64_t index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), indexes); DimensionVector minor_scan_indexes(rank, 0); std::copy(indexes.begin(), indexes.end(), minor_scan_indexes.begin()); char* dest_ptr = dest_base + index * primitive_size; char* const dest_end = dest_base + // This handles the case where minor_loop_size does not evenly divide // the most minor dimension. std::min(index + stride_config.minor_loop_size, num_elements) * primitive_size; while (dest_ptr < dest_end) { populator(dest_ptr, minor_scan_indexes, thread_id); ++minor_scan_indexes[stride_config.minor_dimension]; dest_ptr += primitive_size; } return true; }; if (parallel) { ShapeUtil::ForEachIndexParallel(this_shape, stride_config.base, stride_config.dimensions, stride_config.step, init_function); } else { ShapeUtil::ForEachIndex( this_shape, stride_config.base, stride_config.dimensions, stride_config.step, [&init_function]( absl::Span<const int64_t> indexes) -> absl::StatusOr<bool> { auto result_ignored = init_function(indexes, /*thread_id=*/-1); return true; }); } } else { // For scalars. populator(dest_base, {}, /*thread_id=*/-1); } } auto init_function = [&](absl::Span<const int64_t> indexes, int thread_id) -> absl::StatusOr<bool> { const int64_t index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), indexes); DimensionVector minor_scan_indexes(rank, 0); std::copy(indexes.begin(), indexes.end(), minor_scan_indexes.begin()); char* dest_ptr = dest_base + index * primitive_size; char* const dest_end = dest_base + // This handles the case where minor_loop_size does not evenly divide // the most minor dimension. std::min(index + stride_config.minor_loop_size, num_elements) * primitive_size; while (dest_ptr < dest_end) { populator(dest_ptr, minor_scan_indexes, thread_id); ++minor_scan_indexes[stride_config.minor_dimension]; dest_ptr += primitive_size; } return true; }; [&init_function]( absl::Span<const int64_t> indexes) -> absl::StatusOr<bool> { auto result_ignored = init_function(indexes, /*thread_id=*/-1); return true; }); absl::Status MutableLiteralBase::PopulateInplace( absl::FunctionRef<void(void*, absl::Span<const int64_t>)> populator) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); PopulateInplaceInternal( [&](void* dest, absl::Span<const int64_t> indexes, int /*thread_id*/) { return populator(dest, indexes); }, /*parallel=*/false); return absl::OkStatus(); } absl::Status MutableLiteralBase::PopulateInplaceParallel( absl::FunctionRef<void(void*, absl::Span<const int64_t>, int)> populator) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); PopulateInplaceInternal(populator, /*parallel=*/element_count() > 32); return absl::OkStatus(); } Literal LiteralBase::Relayout(const Layout& new_layout, const ShapeIndex& shape_index) const { // Create new shape with 'new_layout' set at the given shape index. Shape new_shape = shape(); Shape* subshape = ShapeUtil::GetMutableSubshape(&new_shape, shape_index); TF_CHECK_OK(LayoutUtil::ValidateLayoutForShape(new_layout, *subshape)); *subshape->mutable_layout() = new_layout; // LINT.IfChange // s4 literals are stored in uint8_t/int8_t, therefore element_size_in_bits // must be removed. if (subshape->layout().element_size_in_bits() == 4) { subshape->mutable_layout()->set_element_size_in_bits(0); } // LINT.ThenChange(//tensorflow/compiler/xla/types.h) Literal result(new_shape); TF_CHECK_OK(result.CopyFrom(*this)); return result; } Literal LiteralBase::Relayout(const Shape& shape_with_layout) const { CHECK(ShapeUtil::Compatible(shape_with_layout, shape())) << "Given shape_with_layout " << ShapeUtil::HumanString(shape_with_layout) << " not compatible with literal shape " << ShapeUtil::HumanString(shape()); Literal result = CreateFromShape(shape_with_layout); ShapeUtil::ForEachSubshape( result.shape(), [this, &result](const Shape& subshape, const ShapeIndex& index) { if (subshape.IsArray()) { TF_CHECK_OK(result.CopyFrom(*this, /*dest_shape_index=*/index, /*src_shape_index=*/index)); } }); return result; } [this, &result](const Shape& subshape, const ShapeIndex& index) { if (subshape.IsArray()) { TF_CHECK_OK(result.CopyFrom(*this, /*dest_shape_index=*/index, /*src_shape_index=*/index)); } }); Literal LiteralBase::ToBoundedDynamic(const Shape& bounded_shape) const { CHECK(bounded_shape.is_dynamic()); Literal result(bounded_shape); ShapeUtil::ForEachSubshape( shape(), [&](const Shape& subshape, const ShapeIndex& index) { if (!subshape.IsArray()) { return; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (bounded_shape.is_dynamic_dimension(i)) { result.SetDynamicSize(i, subshape.dimensions(i)); } } }); TF_CHECK_OK(result.CopyFrom(*this, {}, {}, /*only_dynamic_bound=*/true)); return result; } shape(), [&](const Shape& subshape, const ShapeIndex& index) { if (!subshape.IsArray()) { return; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (bounded_shape.is_dynamic_dimension(i)) { result.SetDynamicSize(i, subshape.dimensions(i)); } } }); Literal LiteralBase::ToStatic() const { // Create new shape with 'new_layout' set at the given shape index. Shape new_shape = shape(); ShapeUtil::ForEachMutableSubshape( &new_shape, [this](Shape* subshape, const ShapeIndex& index) { if (!subshape->IsArray()) { return; } for (int64_t i = 0; i < subshape->rank(); ++i) { // GetDynamicSize has a 32-bit return type and may truncate static // dimensions, so make sure to skip. if (!subshape->is_dynamic_dimension(i)) continue; subshape->set_dynamic_dimension(i, false); subshape->set_dimensions(i, GetDynamicSize(i, index)); } }); Literal result(new_shape); TF_CHECK_OK(result.CopyFrom(*this, {}, {}, /*only_dynamic_bound=*/true)); return result; } &new_shape, [this](Shape* subshape, const ShapeIndex& index) { if (!subshape->IsArray()) { return; } for (int64_t i = 0; i < subshape->rank(); ++i) { // GetDynamicSize has a 32-bit return type and may truncate static // dimensions, so make sure to skip. if (!subshape->is_dynamic_dimension(i)) continue; subshape->set_dynamic_dimension(i, false); subshape->set_dimensions(i, GetDynamicSize(i, index)); } }); absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { absl::StatusOr<Literal> LiteralBase::Broadcast( const Shape& result_shape, absl::Span<const int64_t> dimensions) const { const LiteralBase& src = *this; const Shape& src_shape = shape(); if (!src_shape.IsArray()) { return InvalidArgument("Broadcast only supports arrays."); } const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(src_shape.element_type()); switch (primitive_size) { case 0: return BroadcastHelper<0>(src, src_shape, result_shape, dimensions); case 1: return BroadcastHelper<1>(src, src_shape, result_shape, dimensions); case 2: return BroadcastHelper<2>(src, src_shape, result_shape, dimensions); case 4: return BroadcastHelper<4>(src, src_shape, result_shape, dimensions); case 8: return BroadcastHelper<8>(src, src_shape, result_shape, dimensions); case 16: return BroadcastHelper<16>(src, src_shape, result_shape, dimensions); default: LOG(FATAL) << "Unhandled primitive size " << primitive_size; return InvalidArgument("Unhandled primitive size"); break; } } absl::StatusOr<Literal> LiteralBase::Reshape( absl::Span<const int64_t> dimensions) const { if (!LayoutUtil::IsDenseArray(shape())) { return InvalidArgument("Reshape is only supported for dense arrays."); } if (shape().is_dynamic()) { // TODO(b/243182930): We should consider supporting dynamic reshape. return Unimplemented("Dynamic reshape is not implemented."); } Literal output; if (!LayoutUtil::IsMonotonicWithDim0Major(shape().layout())) { output = Relayout(LayoutUtil::GetDefaultLayoutForRank(shape().rank())); } else { output = Clone(); } // Because the layout is monotonic, we can simply reuse the same sequence of // values without changing their order. *output.mutable_shape_do_not_use() = ShapeUtil::MakeShape(shape().element_type(), dimensions); int64_t elements_before = ShapeUtil::ElementsIn(shape()); int64_t elements_after = ShapeUtil::ElementsIn(output.shape()); if (elements_before != elements_after) { return InvalidArgument( "Shapes before and after Literal::Reshape have different numbers " "of elements: %s vs %s.", ShapeUtil::HumanString(shape()), ShapeUtil::HumanString(output.shape())); } return std::move(output); } Literal LiteralBase::Transpose(absl::Span<const int64_t> permutation) const { CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); CHECK(shape().rank() == permutation.size() && IsPermutation(permutation)) << "Given permutation is not a permutation of dimension numbers"; // To transpose the array, we just permute the dimensions and layout, and // do a straight memory copy of the raw data set. // This is considerably faster than iterating over every array element using // the EachCell<>() and Set<>() APIs. Shape permuted_shape = ShapeUtil::PermuteDimensions(permutation, shape()); // Replace the layout with one affine to this shape, such that a // transpose operation can be performed by leaving the flat values // representation intact. // For example, consider the shape F32[11,8]{1,0} under a {1,0} permutation. // The shape with affine layout resulting from that operation will be // F32[8,11]{0,1}, since it leaves the original most minor (the 8 sized), the // most minor. // // Essentially, given MinMaj(Di) the position of the Di dimension within the // minor to major vector, and given T(Di) the index that the original Di // dimension has within the transposed array, a layout is affine if // MinMaj(Di) == TMinMaj(T(Di)), with TMinMaj() being the minor to major // vector of the affine layout. std::vector<int64_t> inverse_permutation = InversePermutation(permutation); CHECK(LayoutUtil::IsDenseArray(permuted_shape)); Layout* layout = permuted_shape.mutable_layout(); layout->clear_minor_to_major(); for (auto index : LayoutUtil::MinorToMajor(shape())) { layout->add_minor_to_major(inverse_permutation[index]); } Literal new_literal(permuted_shape); if (shape().is_dynamic()) { for (int64_t i = 0; i < shape().rank(); i++) { if (shape().is_dynamic_dimension(i)) { // Set the dynamic size of any dynamic dimension in the transposed // literal. new_literal.SetDynamicSize(inverse_permutation[i], GetDynamicSize(i)); } } } DCHECK_EQ(ShapeUtil::ByteSizeOf(new_literal.shape()), ShapeUtil::ByteSizeOf(shape())); std::memcpy(new_literal.untyped_data(), untyped_data(), size_bytes()); return new_literal; } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( Literal LiteralBase::Slice(absl::Span<const int64_t> start_indices, absl::Span<const int64_t> limit_indices) const { CHECK(shape().IsArray()) << "tuple is not supported for slice"; DimensionVector result_dimensions; for (int64_t dnum = 0; dnum < shape().rank(); ++dnum) { CHECK_GE(start_indices[dnum], 0); CHECK_LE(limit_indices[dnum], shape().dimensions(dnum)) << "dnum = " << dnum; int64_t dimension = limit_indices[dnum] - start_indices[dnum]; CHECK_GE(dimension, 0) << "dnum = " << dnum; result_dimensions.push_back(dimension); } auto result_shape = ShapeUtil::MakeShapeWithDenseLayout( shape().element_type(), result_dimensions, LayoutUtil::MinorToMajor(shape())); ShapeUtil::CopyDynamicDimensions(&result_shape, shape()); Literal result_literal(result_shape); primitive_util::ArrayTypeSwitch<void>( [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; return SliceInternal<NativeT>(*this, start_indices, result_literal); }, result_shape.element_type()); return result_literal; } Literal LiteralBase::Clone() const { Literal result(shape()); TF_CHECK_OK(result.CopyFrom(*this)); return result; } std::unique_ptr<Literal> LiteralBase::CloneToUnique() const { auto result = std::make_unique<Literal>(shape()); TF_CHECK_OK(result->CopyFrom(*this)); return result; } bool LiteralBase::IsDetermined(const ShapeIndex& shape_index) const { return piece(shape_index).IsDetermined(); } bool LiteralBase::IsKnown(const ShapeIndex& shape_index) const { return piece(shape_index).IsKnown(); } std::string LiteralBase::GetAsString(absl::Span<const int64_t> multi_index, const ShapeIndex& shape_index) const { const Shape& subshape = ShapeUtil::GetSubshape(shape(), shape_index); CHECK(LayoutUtil::IsDenseArray(subshape)); return primitive_util::ArrayTypeSwitch<std::string>( [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, subshape.element_type()); } [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, std::optional<int64_t> LiteralBase::GetIntegralAsS64( absl::Span<const int64_t> multi_index) const { CHECK(LayoutUtil::IsDenseArray(shape())); return primitive_util::PrimitiveTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, std::optional<double> LiteralBase::GetAsDouble( absl::Span<const int64_t> multi_index) const { const Shape& s = shape(); CHECK(LayoutUtil::IsDenseArray(s)); return primitive_util::PrimitiveTypeSwitch<std::optional<double>>( [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, s.element_type()); } [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, std::optional<double> LiteralBase::GetSumAsDouble( absl::Span<const int64_t> linear_indices) const { const Shape& s = shape(); CHECK(LayoutUtil::IsDenseArray(s)); if (!primitive_util::IsFloatingPointType(s.element_type())) { return std::nullopt; } return primitive_util::FloatingPointTypeSwitch<double>( [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, s.element_type()); } [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, std::optional<complex128> LiteralBase::GetAsComplex128( absl::Span<const int64_t> multi_index) const { return primitive_util::PrimitiveTypeSwitch<std::optional<complex128>>( [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, absl::Status MutableLiteralBase::SetIntegralAsS64( absl::Span<const int64_t> multi_index, int64_t value) { CHECK(LayoutUtil::IsDenseArray(shape())); return primitive_util::PrimitiveTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, absl::Status MutableLiteralBase::SetFromDouble( absl::Span<const int64_t> multi_index, double value) { CHECK(LayoutUtil::IsDenseArray(shape())); if (!primitive_util::IsFloatingPointType(shape().element_type())) { return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); } primitive_util::FloatingPointTypeSwitch<void>( [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, shape().element_type()); return absl::OkStatus(); } [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, void PrintShape(bool print_layout, const Shape& shape, Printer* printer) { if (print_layout) { ShapeUtil::PrintHumanStringWithLayout(printer, shape); } else { ShapeUtil::PrintHumanString(printer, shape); } } void TuplePrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); printer->Append(oneline ? "( " : "(\n"); for (int i = 0; i < ShapeUtil::TupleElementCount(subshape); ++i) { ShapeIndex element_index = shape_index; element_index.push_back(i); if (i > 0) printer->Append(oneline ? ", " : ",\n"); PrintHelper(literal, element_index, print_shape, print_layout, oneline, printer); } printer->Append(oneline ? " )" : "\n)"); } void DenseArrayPrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); int64_t rank = subshape.rank(); const absl::string_view linebreak = oneline ? " " : "\n"; std::function<void(absl::Span<const int64_t> dimensions, std::vector<int64_t>*)> print_recursive = [&](absl::Span<const int64_t> dimensions, std::vector<int64_t>* accum_indices) { // dimensions.size() decreases by 1 at each recursive call, // and accum_indices->size() increases by 1. // Their sum is equal to the rank of the tensor. CHECK_EQ(rank, dimensions.size() + accum_indices->size()); auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; if (dimensions.empty()) { // Display predicates as 0s and 1s so that the string is more dense. std::string elem; if (subshape.element_type() == PRED && rank > 0) { elem = literal.Get<bool>(*accum_indices, shape_index) ? "1" : "0"; } else { elem = literal.GetAsString(*accum_indices, shape_index); } printer->Append(elem); } else { printer->Append(brace_to_string("{")); for (int i = 0; i < dimensions[0]; ++i) { accum_indices->push_back(i); print_recursive(dimensions.subspan(1), accum_indices); accum_indices->pop_back(); if (i < dimensions[0] - 1) { printer->Append(","); printer->Append(dimensions.size() > 1 ? linebreak : " "); } } printer->Append(brace_to_string("}")); } }; if (print_shape) { PrintShape(print_layout, subshape, printer); if (subshape.is_dynamic()) { printer->Append("("); for (int64_t i = 0; i < subshape.dimensions_size(); ++i) { printer->Append(literal.GetDynamicSize(i, shape_index)); if (i < subshape.dimensions_size() - 1) { printer->Append(","); } } printer->Append(")"); } printer->Append(" "); } std::vector<int64_t> indices = {}; std::vector<int64_t> dimensions; dimensions.reserve(subshape.rank()); for (int64_t i = 0; i < subshape.rank(); ++i) { dimensions.push_back(literal.GetDynamicSize(i, shape_index)); } print_recursive(dimensions, &indices); } print_recursive = [&](absl::Span<const int64_t> dimensions, std::vector<int64_t>* accum_indices) { // dimensions.size() decreases by 1 at each recursive call, // and accum_indices->size() increases by 1. // Their sum is equal to the rank of the tensor. CHECK_EQ(rank, dimensions.size() + accum_indices->size()); auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; if (dimensions.empty()) { // Display predicates as 0s and 1s so that the string is more dense. std::string elem; if (subshape.element_type() == PRED && rank > 0) { elem = literal.Get<bool>(*accum_indices, shape_index) ? "1" : "0"; } else { elem = literal.GetAsString(*accum_indices, shape_index); } printer->Append(elem); } else { printer->Append(brace_to_string("{")); for (int i = 0; i < dimensions[0]; ++i) { accum_indices->push_back(i); print_recursive(dimensions.subspan(1), accum_indices); accum_indices->pop_back(); if (i < dimensions[0] - 1) { printer->Append(","); printer->Append(dimensions.size() > 1 ? linebreak : " "); } } printer->Append(brace_to_string("}")); } }; auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; void PrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); CHECK(LayoutUtil::HasLayout(literal.shape())); CHECK(LayoutUtil::HasLayout(subshape)); if (subshape.IsTuple()) { TuplePrintHelper(literal, shape_index, print_shape, print_layout, oneline, printer); } else if (subshape.IsToken()) { printer->Append("token"); } else { CHECK(LayoutUtil::IsDenseArray(subshape)); if (literal.IsKnown(shape_index)) { DenseArrayPrintHelper(literal, shape_index, print_shape, print_layout, oneline, printer); } else { PrintShape(print_layout, subshape, printer); printer->Append(" "); if (literal.IsDetermined(shape_index)) { printer->Append("unknown"); } else { printer->Append("undetermined"); } } } } void LiteralBase::Print(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/false, /*oneline=*/false, printer); } void LiteralBase::PrintOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/false, /*oneline=*/true, printer); } void LiteralBase::PrintWithoutShape(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/false, /*print_layout=*/false, /*oneline=*/false, printer); } void LiteralBase::PrintWithoutShapeOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/false, /*print_layout=*/false, /*oneline=*/true, printer); } void LiteralBase::PrintWithLayout(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/true, /*oneline=*/false, printer); } void LiteralBase::PrintWithLayoutOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/true, /*oneline=*/true, printer); } std::string LiteralBase::ToString() const { StringPrinter printer; Print(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringOneline() const { StringPrinter printer; PrintOneline(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithoutShape() const { StringPrinter printer; PrintWithoutShape(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithoutShapeOneline() const { StringPrinter printer; PrintWithoutShapeOneline(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithLayout() const { StringPrinter printer; PrintWithLayout(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithLayoutOneline() const { StringPrinter printer; PrintWithLayoutOneline(&printer); return std::move(printer).ToString(); } void LiteralBase::EachCellAsString( absl::FunctionRef<void(absl::Span<const int64_t> indices, const std::string& value)> per_cell) const { if (ShapeUtil::IsZeroElementArray(shape())) { return; } auto indices = IndexUtil::LinearIndexToMultidimensionalIndex( shape(), /*linear_index=*/0); do { per_cell(indices, GetAsString(indices)); } while (IndexUtil::BumpIndices(shape(), absl::MakeSpan(indices))); } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { absl::StatusOr<Literal> ConvertSwitch(const LiteralBase& literal, PrimitiveType primitive_dest_type) { TF_RET_CHECK(LayoutUtil::IsDenseArray(literal.shape())); if (literal.shape().element_type() == primitive_dest_type) { return literal.Clone(); } // Source Array type requirement is ensured by IsDenseArray before. if (!primitive_util::IsArrayType(primitive_dest_type) || !primitive_util::IsArrayType(literal.shape().element_type())) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(literal.shape().element_type()), PrimitiveType_Name(primitive_dest_type)); } // At this point, we know both src & dst are array types, while src is not // complex type, so we can allocate the result literal here to avoid // duplicating it N^2 times in the conversion implementation. Literal result( ShapeUtil::ChangeElementType(literal.shape(), primitive_dest_type)); TF_RETURN_IF_ERROR(primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { return ConvertIfDestTypeMatches<primitive_type_constant>(literal, result); }, literal.shape().element_type())); return result; } absl::StatusOr<Literal> LiteralBase::Convert( PrimitiveType primitive_dest_type) const { return ConvertSwitch(*this, primitive_dest_type); } absl::StatusOr<Literal> LiteralBase::BitcastConvert( const Shape& dest_shape) const { if (ShapeUtil::ByteSizeOf(dest_shape) != ShapeUtil::ByteSizeOf(shape())) { return InvalidArgument( "Can not bitcast-convert from shape %s to a shape of different size %s", shape().ToString(), dest_shape.ToString()); } if (dest_shape.IsTuple() || shape().IsTuple()) { return InvalidArgument( "bitcast-convert is not valid for tuple shapes %s->%s", shape().ToString(), dest_shape.ToString()); } if (shape().is_dynamic() || dest_shape.is_dynamic()) { return InvalidArgument( "bitcast-convert is not valid for dynamic shape %s->%s", shape().ToString(), dest_shape.ToString()); } Literal out(dest_shape); std::memcpy(out.root_piece_.buffer(), root_piece().buffer(), root_piece().size_bytes_dense()); // Perform the reshape on little endian encoding even on big endian machines. if constexpr (!kLittleEndian) { // Swap byte ordering as per the input data type. size_t input_elem_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); TF_RETURN_IF_ERROR(tsl::ByteSwapArray( const_cast<char*>(out.root_piece().buffer()), input_elem_size, out.root_piece().size_bytes_dense() / input_elem_size)); // Swap byte ordering as per the output data type. size_t output_elem_size = ShapeUtil::ByteSizeOfPrimitiveType(dest_shape.element_type()); TF_RETURN_IF_ERROR(tsl::ByteSwapArray( const_cast<char*>(out.root_piece().buffer()), output_elem_size, out.root_piece().size_bytes_dense() / output_elem_size)); } return out; } absl::StatusOr<Literal> LiteralBase::ConvertToShape( const Shape& dest_shape) const { if (!dest_shape.IsTuple()) { return Convert(dest_shape.element_type()); } std::vector<Literal> elements; const auto tuple_element_count = ShapeUtil::TupleElementCount(shape()); elements.reserve(tuple_element_count); for (int i = 0; i < tuple_element_count; ++i) { auto element = LiteralSlice(*this, {i}); TF_ASSIGN_OR_RETURN( auto new_element, element.ConvertToShape(ShapeUtil::GetSubshape(dest_shape, {i}))); elements.push_back(std::move(new_element)); } return MutableLiteralBase::MoveIntoTuple(absl::MakeSpan(elements)); } /* static */ Literal MutableLiteralBase::MoveIntoTuple( absl::Span<Literal> elements) { std::vector<const Shape*> element_shapes; element_shapes.reserve(elements.size()); for (const Literal& element : elements) { element_shapes.push_back(&element.shape()); } Literal literal(ShapeUtil::MakeTupleShapeWithPtrs(element_shapes), /*allocate_arrays=*/false); for (int i = 0, end = elements.size(); i < end; ++i) { TF_CHECK_OK( literal.MoveFrom(std::move(elements[i]), /*dest_shape_index=*/{i})); } return literal; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualDynamicSize( const LiteralBase::Piece& other) const { DCHECK(ShapeUtil::Compatible(subshape(), other.subshape())); if (subshape().is_static()) { return true; } for (int64_t i = 0; i < subshape().rank(); ++i) { if (GetDynamicSize(i) != other.GetDynamicSize(i)) { return false; } } return true; } bool LiteralBase::Piece::EqualElements(const LiteralBase::Piece& other) const { if (subshape().is_static() && ShapeUtil::Equal(subshape(), other.subshape()) && subshape().IsArray()) { CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(size_bytes_dense(), other.size_bytes_dense()); if (primitive_util::IsSubByteNonPredType(subshape().element_type())) { CHECK(!primitive_util::IsFloatingPointType(subshape().element_type())); auto one_array = buffer(); auto two_array = other.buffer(); const int bits_per_element = primitive_util::BitWidth(subshape().element_type()); const uint8_t mask = LsbMask<uint8_t>(bits_per_element); for (int64_t i = 0; i < size_bytes_dense(); ++i) { if ((one_array[i] & mask) != (two_array[i] & mask)) return false; } return true; } return memcmp(buffer(), other.buffer(), size_bytes_dense()) == 0; } std::vector<int64_t> multi_index; return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeSrcT = NativeTypeOf<primitive_type_constant>; return EqualElementsInternal<NativeSrcT>(other, &multi_index); }, subshape().element_type()); } bool LiteralBase::Equal(const LiteralBase& other, bool layout_sensitive) const { // Checking the structure of tuple literals. Checks for dense arrays are // performed below. if (!ShapeUtil::EqualStructure(shape(), other.shape())) { return false; } return root_piece().ForEachSubpieceWithBool([&](const ShapeIndex& index, const Piece& piece) { const Piece& other_piece = other.piece(index); const Shape& subshape = piece.subshape(); const Shape& other_subshape = other_piece.subshape(); if (subshape.element_type() != other_subshape.element_type()) { return false; } if (!piece.subshape().IsArray()) { return true; } if (subshape.rank() != other_subshape.rank()) { return false; } if (layout_sensitive && (subshape.layout() != other_subshape.layout())) { return false; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (piece.GetDynamicSize(i) != other_piece.GetDynamicSize(i)) { return false; } } if (!piece.EqualElements(other_piece)) { return false; } return true; }); } return root_piece().ForEachSubpieceWithBool([&](const ShapeIndex& index, const Piece& piece) { const Piece& other_piece = other.piece(index); const Shape& subshape = piece.subshape(); const Shape& other_subshape = other_piece.subshape(); if (subshape.element_type() != other_subshape.element_type()) { return false; } if (!piece.subshape().IsArray()) { return true; } if (subshape.rank() != other_subshape.rank()) { return false; } if (layout_sensitive && (subshape.layout() != other_subshape.layout())) { return false; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (piece.GetDynamicSize(i) != other_piece.GetDynamicSize(i)) { return false; } } if (!piece.EqualElements(other_piece)) { return false; } return true; }); static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(std::complex<T> a, std::complex<T> b) { return EqualIncludingNan(a.real(), b.real()) && EqualIncludingNan(a.imag(), b.imag()); } static bool EqualIncludingNan(std::complex<T> a, std::complex<T> b) { return EqualIncludingNan(a.real(), b.real()) && EqualIncludingNan(a.imag(), b.imag()); } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } bool Literal::Piece::IsAll(const Literal& scalar) const { CHECK(ShapeUtil::IsScalar(scalar.shape())) << scalar.shape().ToString(); if (!subshape().IsArray()) { return false; } CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(subshape().element_type(), scalar.shape().element_type()); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, subshape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, int64_t Literal::Piece::CountAll(const Literal& scalar) const { CHECK(ShapeUtil::IsScalar(scalar.shape())) << scalar.shape().ToString(); if (!subshape().IsArray()) { return 0; } CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(subshape().element_type(), scalar.shape().element_type()); return primitive_util::ArrayTypeSwitch<int64_t>( [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, subshape().element_type()); } [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { bool LiteralBase::IsAll(const Literal& scalar) const { return root_piece().IsAll(scalar); } bool LiteralBase::IsAll(int8_t value) const { if (!shape().IsArray()) { return false; } PrimitiveType ty = shape().element_type(); if (primitive_util::IsFloatingPointType(ty)) { return IsAllFloatImpl(value, /*round_value=*/false); } if (primitive_util::IsUnsignedIntegralType(ty) && value < 0) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllFloat(float value) const { return IsAllFloatImpl(value, /*round_value=*/true); } bool LiteralBase::IsAllFloatImpl(float value, bool round_value) const { PrimitiveType ty = shape().element_type(); if (!primitive_util::IsFloatingPointType(ty)) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::FloatingPointTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllComplex(complex64 value) const { PrimitiveType ty = shape().element_type(); if (!primitive_util::IsComplexType(ty)) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::ComplexTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllFirst() const { if (!shape().IsArray()) { return false; } // Empty shapes are not all the first element since there is no first element. if (ShapeUtil::IsZeroElementArray(shape())) { return false; } absl::InlinedVector<int64_t, 4> start_indices(/*n=*/shape().rank(), 0); absl::InlinedVector<int64_t, 4> end_indices(/*n=*/shape().rank(), 1); Literal first = Slice(start_indices, end_indices); return IsAll(first.Reshape({}).value()); } bool LiteralBase::IsR1Iota() const { if (!shape().IsArray()) { return false; } CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); if (shape().rank() != 1) { return false; } return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, shape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, std::optional<int64_t> LiteralBase::IsR1StridedIota() const { if (!shape().IsArray() || shape().rank() != 1) { return std::nullopt; } CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); const int64_t elements = ShapeUtil::ElementsIn(shape()); const PrimitiveType type = shape().element_type(); if (elements <= 1 || !primitive_util::IsIntegralType(type)) { return std::nullopt; } return primitive_util::IntegralTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, bool LiteralBase::IsZero(absl::Span<const int64_t> indices) const { CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, shape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void LiteralBase::Piece::set_array_value_state(ArrayValueState state) { array_value_state_ = state; } LiteralBase::ArrayValueState LiteralBase::Piece::get_array_value_state() const { return array_value_state_; } void LiteralBase::Piece::WriteToProto(LiteralProto* proto) const { *proto->mutable_shape() = subshape().ToProto(); switch (subshape().element_type()) { case PRED: CopyToRepeatedField(proto->mutable_preds(), data<bool>()); break; case U2: *proto->mutable_u2s() = std::string( reinterpret_cast<const char*>(data<u2>().data()), size_bytes_dense()); break; case U4: *proto->mutable_u4s() = std::string( reinterpret_cast<const char*>(data<u4>().data()), size_bytes_dense()); break; case U8: proto->set_u8s(static_cast<const unsigned char*>(data<uint8_t>().data()), element_count()); break; case U16: *proto->mutable_u16s() = std::string(reinterpret_cast<const char*>(data<uint16_t>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_u16s()); } break; case U32: CopyToRepeatedField(proto->mutable_u32s(), data<uint32_t>()); break; case U64: CopyToRepeatedField(proto->mutable_u64s(), data<uint64_t>()); break; case S2: *proto->mutable_s2s() = std::string( reinterpret_cast<const char*>(data<s2>().data()), size_bytes_dense()); break; case S4: *proto->mutable_s4s() = std::string( reinterpret_cast<const char*>(data<s4>().data()), size_bytes_dense()); break; case S8: proto->set_s8s(static_cast<const signed char*>(data<int8_t>().data()), element_count()); break; case S16: *proto->mutable_s16s() = std::string(reinterpret_cast<const char*>(data<int16_t>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_s16s()); } break; case S32: CopyToRepeatedField(proto->mutable_s32s(), data<int32_t>()); break; case S64: CopyToRepeatedField(proto->mutable_s64s(), data<int64_t>()); break; case F8E5M2: *proto->mutable_f8e5m2s() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e5m2>().data()), size_bytes_dense()); break; case F8E4M3FN: *proto->mutable_f8e4m3fns() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3fn>().data()), size_bytes_dense()); break; case F8E4M3B11FNUZ: *proto->mutable_f8e4m3b11fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3b11fnuz>().data()), size_bytes_dense()); break; case F8E5M2FNUZ: *proto->mutable_f8e5m2fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e5m2fnuz>().data()), size_bytes_dense()); break; case F8E4M3FNUZ: *proto->mutable_f8e4m3fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3fnuz>().data()), size_bytes_dense()); break; case F16: *proto->mutable_f16s() = std::string(reinterpret_cast<const char*>(data<half>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_f16s()); } break; case BF16: *proto->mutable_bf16s() = std::string(reinterpret_cast<const char*>(data<bfloat16>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_bf16s()); } break; case F32: CopyToRepeatedField(proto->mutable_f32s(), data<float>()); break; case F64: CopyToRepeatedField(proto->mutable_f64s(), data<double>()); break; case C64: for (complex64 value : data<complex64>()) { proto->add_c64s(value.real()); proto->add_c64s(value.imag()); } break; case C128: for (complex128 value : data<complex128>()) { proto->add_c128s(value.real()); proto->add_c128s(value.imag()); } break; case TUPLE: case TOKEN: // Nothing to do but assign the shape which is done above. return; default: // TODO(b/111551621): Support serializing more PrimitiveTypes. LOG(FATAL) << "Unhandled primitive type " << PrimitiveType_Name(subshape().element_type()); } } const void* LiteralBase::Piece::untyped_data() const { DCHECK(LayoutUtil::IsDenseArray(subshape())) << ShapeUtil::HumanString(subshape()); return buffer(); } void* LiteralBase::Piece::untyped_data() { DCHECK(LayoutUtil::IsDenseArray(subshape())) << ShapeUtil::HumanString(subshape()); return buffer(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status LiteralBase::Piece::CopyFromProto(const LiteralProto& proto) { // These conditions should have been checked in // MutableLiteralBase::CreateFromProto. TF_RET_CHECK(proto.has_shape()); Shape shape(proto.shape()); TF_RET_CHECK(LayoutUtil::HasLayout(shape)); TF_RET_CHECK(ShapeUtil::Equal(shape, subshape())); switch (subshape().element_type()) { case PRED: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<bool>(), proto.preds())); break; case S2: { const std::string& s(proto.s2s()); TF_RET_CHECK(data<s2>().size() * sizeof(s2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case S4: { const std::string& s(proto.s4s()); TF_RET_CHECK(data<s4>().size() * sizeof(s4) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case S8: { auto s8_data = data<int8_t>(); TF_RET_CHECK(proto.s8s().size() == s8_data.size()); std::copy(proto.s8s().begin(), proto.s8s().end(), s8_data.begin()); break; } case S16: { const std::string& s(proto.s16s()); TF_RET_CHECK(data<int16_t>().size() * sizeof(int16_t) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case S32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<int32_t>(), proto.s32s())); break; case S64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<int64_t>(), proto.s64s())); break; case U2: { const std::string& s(proto.u2s()); TF_RET_CHECK(data<u2>().size() * sizeof(u2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case U4: { const std::string& s(proto.u4s()); TF_RET_CHECK(data<u4>().size() * sizeof(u4) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case U8: { auto u8_data = data<uint8_t>(); TF_RET_CHECK(proto.u8s().size() == u8_data.size()); std::copy(proto.u8s().begin(), proto.u8s().end(), u8_data.begin()); break; } case U16: { const std::string& s(proto.u16s()); TF_RET_CHECK(data<uint16_t>().size() * sizeof(uint16_t) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case U32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<uint32_t>(), proto.u32s())); break; case U64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<uint64_t>(), proto.u64s())); break; case F8E5M2: { const std::string& s(proto.f8e5m2s()); TF_RET_CHECK(data<tsl::float8_e5m2>().size() * sizeof(tsl::float8_e5m2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3FN: { const std::string& s(proto.f8e4m3fns()); TF_RET_CHECK(data<tsl::float8_e4m3fn>().size() * sizeof(tsl::float8_e4m3fn) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3B11FNUZ: { const std::string& s(proto.f8e4m3b11fnuzs()); TF_RET_CHECK(data<tsl::float8_e4m3b11fnuz>().size() * sizeof(tsl::float8_e4m3b11fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E5M2FNUZ: { const std::string& s(proto.f8e5m2fnuzs()); TF_RET_CHECK(data<tsl::float8_e5m2fnuz>().size() * sizeof(tsl::float8_e5m2fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3FNUZ: { const std::string& s(proto.f8e4m3fnuzs()); TF_RET_CHECK(data<tsl::float8_e4m3fnuz>().size() * sizeof(tsl::float8_e4m3fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F16: { const std::string& s(proto.f16s()); TF_RET_CHECK(data<half>().size() * sizeof(half) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case BF16: { const std::string& s(proto.bf16s()); TF_RET_CHECK(data<bfloat16>().size() * sizeof(bfloat16) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case F32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<float>(), proto.f32s())); break; case F64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<double>(), proto.f64s())); break; case C64: { auto complex_data = data<complex64>(); TF_RET_CHECK(proto.c64s_size() == complex_data.size() * 2); for (int64_t i = 0; i < complex_data.size(); ++i) { complex_data[i] = complex64{proto.c64s(i * 2), proto.c64s(i * 2 + 1)}; } break; } case C128: { auto complex_data = data<complex128>(); const int64_t complex_data_size_doubled = complex_data.size() * 2; TF_RET_CHECK(proto.c128s_size() == complex_data_size_doubled); for (int64_t i = 0, end = complex_data.size(); i < end; ++i) { complex_data[i] = complex128{proto.c128s(i * 2), proto.c128s(i * 2 + 1)}; } break; } case TUPLE: return InvalidArgument("Should not be called on tuple shapes: %s", ShapeUtil::HumanString(subshape())); default: return InvalidArgument("Is called on unsupported shape: %s", ShapeUtil::HumanString(subshape())); } return absl::OkStatus(); } bool LiteralBase::Piece::IsKnown() const { if (array_value_state_ != ArrayValueState::kKnown) { return false; } if (subshape().IsTuple()) { bool are_all_leaf_arrays_known = true; ForEachSubpiece([&are_all_leaf_arrays_known](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_known &= piece.IsKnown(); }); return are_all_leaf_arrays_known; } return true; } ForEachSubpiece([&are_all_leaf_arrays_known](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_known &= piece.IsKnown(); }); bool LiteralBase::Piece::IsDetermined() const { if (array_value_state_ == ArrayValueState::kUndetermined) { return false; } if (subshape().IsTuple()) { bool are_all_leaf_arrays_determined = true; ForEachSubpiece([&are_all_leaf_arrays_determined](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_determined &= piece.IsDetermined(); }); return are_all_leaf_arrays_determined; } return true; } ForEachSubpiece([&are_all_leaf_arrays_determined](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_determined &= piece.IsDetermined(); }); LiteralProto LiteralBase::ToProto() const { LiteralProto proto; root_piece().ForEachSubpiece( [&](const ShapeIndex& index, const Piece& piece) { LiteralProto* proto_piece = &proto; for (int64_t i : index) { while (proto_piece->tuple_literals_size() <= i) { proto_piece->add_tuple_literals(); } proto_piece = proto_piece->mutable_tuple_literals(i); } piece.WriteToProto(proto_piece); }); return proto; } [&](const ShapeIndex& index, const Piece& piece) { LiteralProto* proto_piece = &proto; for (int64_t i : index) { while (proto_piece->tuple_literals_size() <= i) { proto_piece->add_tuple_literals(); } proto_piece = proto_piece->mutable_tuple_literals(i); } piece.WriteToProto(proto_piece); }); const void* LiteralBase::untyped_data(const ShapeIndex& shape_index) const { return piece(shape_index).untyped_data(); } void* MutableLiteralBase::untyped_data(const ShapeIndex& shape_index) { return piece(shape_index).untyped_data(); } int64_t LiteralBase::size_bytes(const ShapeIndex& shape_index) const { return piece(shape_index).size_bytes_dense(); } std::string LiteralBase::GetR1U8AsString() const { CHECK(shape().IsArray()); CHECK_EQ(shape().rank(), 1); CHECK_EQ(shape().element_type(), U8); return std::string(absl::bit_cast<const char*>(data<uint8_t>().data()), ShapeUtil::ElementsIn(shape())); } void MutableBorrowingLiteral::CopyPieceSubtree(const Shape& shape, const Piece* src_piece, Piece* dest_piece) { DCHECK(ShapeUtil::Equal(src_piece->subshape(), dest_piece->subshape())) << "src_piece has shape: " << ShapeUtil::HumanString(src_piece->subshape()) << "dest_piece has shape: " << ShapeUtil::HumanString(dest_piece->subshape()); dest_piece->set_array_value_state(src_piece->get_array_value_state()); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); Piece child_piece; child_piece.set_subshape(&subshape); CopyPieceSubtree(subshape, &src_piece->child(i), &child_piece); dest_piece->emplace_back(std::move(child_piece)); } } else if (shape.IsArray()) { dest_piece->set_buffer(const_cast<char*>(src_piece->buffer())); } } MutableLiteralBase::~MutableLiteralBase() = default; MutableBorrowingLiteral::MutableBorrowingLiteral( const MutableBorrowingLiteral& literal) : MutableLiteralBase() { shape_ = literal.shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.root_piece(), root_piece_); } MutableBorrowingLiteral& MutableBorrowingLiteral::operator=( const MutableBorrowingLiteral& literal) { shape_ = literal.shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.root_piece(), root_piece_); return *this; } MutableBorrowingLiteral::MutableBorrowingLiteral(MutableLiteralBase* literal) : MutableLiteralBase() { shape_ = literal->shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal->root_piece(), root_piece_); } MutableBorrowingLiteral::MutableBorrowingLiteral( MutableBorrowingLiteral literal, const ShapeIndex& view_root) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(literal.piece(view_root).subshape()); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.piece(view_root), root_piece_); } MutableBorrowingLiteral::MutableBorrowingLiteral(const char* src_buf_ptr, const Shape& shape) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(shape); CHECK(LayoutUtil::HasLayout(*shape_)); CHECK(!shape_->IsTuple()); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); root_piece_->set_buffer(const_cast<char*>(src_buf_ptr)); } MutableBorrowingLiteral::MutableBorrowingLiteral(absl::Span<char*> src_buf_ptrs, const Shape& shape) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(shape); if (!shape_->IsTuple()) { CHECK_EQ(src_buf_ptrs.size(), 1); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); root_piece_->set_buffer(const_cast<char*>(src_buf_ptrs[0])); } else { CHECK(!ShapeUtil::IsNestedTuple(*shape_)); CHECK_EQ(src_buf_ptrs.size(), ShapeUtil::TupleElementCount(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); for (int i = 0; i < src_buf_ptrs.size(); ++i) { Piece child_piece; const auto& src_shape = shape_->tuple_shapes(i); CHECK(src_shape.IsArray()); child_piece.set_subshape(&src_shape); child_piece.set_buffer(src_buf_ptrs[i]); root_piece_->emplace_back(std::move(child_piece)); } } } MutableBorrowingLiteral::MutableBorrowingLiteral(ShapeTree<char*> src_buf_ptrs) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(src_buf_ptrs.shape()); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); BuildPieceSubtree(*shape_, root_piece_); root_piece_->ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); } [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); MutableBorrowingLiteral::~MutableBorrowingLiteral() { if (root_piece_ != nullptr) { delete root_piece_; } } LiteralSlice::LiteralSlice(const LiteralBase& literal) : LiteralBase(), root_piece_(&literal.root_piece()) {} LiteralSlice::LiteralSlice(const LiteralBase& literal, const ShapeIndex& view_root) : LiteralBase(), root_piece_(&literal.piece(view_root)) {} BorrowingLiteral::BorrowingLiteral(const char* src_buf_ptr, const Shape& shape) : LiteralBase(), shape_(std::make_unique<Shape>(shape)) { CHECK(shape_->IsArray()); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); root_piece_.set_buffer(const_cast<char*>(src_buf_ptr)); } BorrowingLiteral::BorrowingLiteral(absl::Span<const char* const> src_buf_ptrs, const Shape& shape) : LiteralBase(), shape_(std::make_unique<Shape>(shape)) { CHECK(shape_->IsTuple()); CHECK(!ShapeUtil::IsNestedTuple(*shape_)); CHECK_EQ(src_buf_ptrs.size(), ShapeUtil::TupleElementCount(*shape_)); root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); BuildPieceSubtree(*shape_, &root_piece_); for (int i = 0, end = src_buf_ptrs.size(); i < end; ++i) { const auto& src_shape = shape_->tuple_shapes(i); CHECK(src_shape.IsArray()); root_piece_.child(i).set_buffer(const_cast<char*>(src_buf_ptrs[i])); } } BorrowingLiteral::BorrowingLiteral(ShapeTree<const char*> src_buf_ptrs) : LiteralBase(), shape_(std::make_unique<Shape>(src_buf_ptrs.shape())) { root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); BuildPieceSubtree(*shape_, &root_piece_); root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); } [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); });
#include "xla/literal.h" #include <algorithm> #include <cmath> #include <complex> #include <cstdint> #include <functional> #include <limits> #include <random> #include <string> #include <tuple> #include <utility> #include <vector> #include "absl/base/casts.h" #include "absl/hash/hash.h" #include "absl/random/random.h" #include "absl/status/status.h" #include "absl/strings/match.h" #include "absl/types/span.h" #include "xla/array.h" #include "xla/array2d.h" #include "xla/array3d.h" #include "xla/array4d.h" #include "xla/index_util.h" #include "xla/layout.h" #include "xla/layout_util.h" #include "xla/literal_util.h" #include "xla/primitive_util.h" #include "xla/shape.h" #include "xla/shape_tree.h" #include "xla/shape_util.h" #include "xla/test.h" #include "xla/types.h" #include "xla/util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/errors.h" #include "tsl/platform/logging.h" // IWYU pragma: keep #include "tsl/platform/macros.h" #include "tsl/platform/ml_dtypes.h" #include "tsl/platform/statusor.h" #include "tsl/platform/test_benchmark.h" class LiteralUtilTest : public ::testing::Test { protected: LiteralUtilTest() { Array4D<float> arr4d({ // clang-format off { // i0=0 { // i1=0 {1, 2, 3}, // i2=0 {4, 5, 6}, // i2=1 {7, 8, 9}, // i2=2 }, { // i1=1 {11, 12, 13}, {14, 15, 16}, {17, 18, 19}, }, }, { // i0=1 { // i1=0 {101, 102, 103}, {104, 105, 106}, {107, 108, 109}, }, { // i1=1 {201, 202, 203}, // i2=0 {204, 205, 206}, // i2=1 {207, 208, 209}, // i2=2 }, }, // clang-format on }); layout_r2_dim0major_ = LayoutUtil::MakeLayout({1, 0}); layout_r2_dim0minor_ = LayoutUtil::MakeLayout({0, 1}); layout_r3_dim0major_ = LayoutUtil::MakeLayout({2, 1, 0}); layout_r3_dim0minor_ = LayoutUtil::MakeLayout({0, 1, 2}); layout_r4_dim0major_ = LayoutUtil::MakeLayout({3, 2, 1, 0}); layout_r4_dim0minor_ = LayoutUtil::MakeLayout({0, 1, 2, 3}); literal_r4_2x2x3x3_dim0major_ = LiteralUtil::CreateR4FromArray4DWithLayout<float>(arr4d, layout_r4_dim0major_); literal_r4_2x2x3x3_dim0minor_ = LiteralUtil::CreateR4FromArray4DWithLayout<float>(arr4d, layout_r4_dim0minor_); } Layout layout_r2_dim0major_; Layout layout_r2_dim0minor_; Layout layout_r3_dim0major_; Layout layout_r3_dim0minor_; Layout layout_r4_dim0major_; Layout layout_r4_dim0minor_; Literal literal_r4_2x2x3x3_dim0major_; Literal literal_r4_2x2x3x3_dim0minor_; };
LiteralUtilTest_ConvertR4
xla/literal_test.cc
bool LiteralProtoHasValues(const LiteralProto& proto) { return !proto.s2s().empty() || !proto.s4s().empty() || !proto.s8s().empty() || !proto.s16s().empty() || proto.s32s_size() || proto.s64s_size() || !proto.u2s().empty() || !proto.u4s().empty() || !proto.u8s().empty() || !proto.u16s().empty() || proto.u32s_size() || proto.u64s_size() || !proto.f8e5m2s().empty() || !proto.f8e4m3fns().empty() || !proto.f8e4m3b11fnuzs().empty() || !proto.f8e5m2fnuzs().empty() || !proto.f8e4m3fnuzs().empty() || !proto.f16s().empty() || !proto.bf16s().empty() || proto.f32s_size() || proto.f64s_size() || proto.c64s_size() || proto.c128s_size() || proto.preds_size() || proto.tuple_literals_size(); } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { const Shape& NilShape() { static const Shape* shape = new Shape(TUPLE, {}, {}, {}); return *shape; } const Shape* TryInternShape(const Shape& shape) { if (shape.IsTuple() && shape.tuple_shapes_size() == 0) { return &NilShape(); } if (shape.IsArray() && shape.dimensions_size() == 0 && shape.is_static() && shape.layout().tiles_size() == 0 && shape.layout().memory_space() == 0) { return &ScalarShape(shape.element_type()); } return nullptr; } StrideConfig::StrideConfig(const Shape& source_shape, const Shape& dest_shape, absl::Span<const int64_t> dimensions) : dimensions(dimensions), base(dimensions.size(), 0), step(dimensions.size(), 1) { if (!dimensions.empty()) { // Selects the shape with the largest minor dimension as the one upon // which to run the tight stride loop. if (dimensions[LayoutUtil::Minor(source_shape.layout(), 0)] >= dimensions[LayoutUtil::Minor(dest_shape.layout(), 0)]) { minor_dimension = LayoutUtil::Minor(source_shape.layout(), 0); dest_stride = IndexUtil::GetDimensionStride(dest_shape, minor_dimension); } else { minor_dimension = LayoutUtil::Minor(dest_shape.layout(), 0); source_stride = IndexUtil::GetDimensionStride(source_shape, minor_dimension); } minor_loop_size = dimensions[minor_dimension]; step[minor_dimension] = minor_loop_size; } } LiteralBase::~LiteralBase() = default; const Shape& LiteralBase::shape() const { return root_piece().subshape(); } const char* LiteralBase::Piece::buffer() const { // std::visit is avoided here due to its code size issues. if (auto* r = std::get_if<DenseRep>(&rep_)) { return r->data; } if (auto* r = std::get_if<DenseInlinedRep>(&rep_)) { return r->data; } DCHECK(std::holds_alternative<TupleRep>(rep_) || std::holds_alternative<Uninitialized>(rep_)); return nullptr; } const LiteralBase::Piece& LiteralBase::piece( const ShapeIndex& shape_index) const { const Piece* piece = &root_piece(); for (const auto i : shape_index) { DCHECK_GE(i, 0); DCHECK_LT(i, piece->children_size()); piece = &piece->child(i); } return *piece; } std::ostream& operator<<(std::ostream& out, const Literal& literal) { out << literal.ToString(); return out; } Shape* MutableLiteralBase::mutable_shape_do_not_use() { const Shape* const_shape = shape_.get(); if (!shape_.OwnsPtr()) { shape_ = MaybeOwningShapePtr(std::make_unique<Shape>(*shape_)); } Shape* shape = shape_.get_mutable(); if (shape != const_shape) { std::function<void(const Shape&, Piece*)> set_piece_shapes = [&set_piece_shapes](const Shape& shape, Piece* piece) { piece->set_subshape(&shape); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); set_piece_shapes(subshape, &piece->child(i)); } } }; set_piece_shapes(*shape, &mutable_root_piece()); } return shape; } [&set_piece_shapes](const Shape& shape, Piece* piece) { piece->set_subshape(&shape); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); set_piece_shapes(subshape, &piece->child(i)); } } }; Literal::Literal() : Literal(NilShape()) {} Literal::Literal(const Shape& shape) : Literal(shape, /*allocate_arrays=*/true) {} void Literal::SetShape(const Shape& shape) { Shape shape_storage; const Shape* shape_ptr = &shape; if (LayoutUtil::HasCustomElementSizeInBits(shape)) { shape_storage = shape; shape_storage.mutable_layout()->set_element_size_in_bits(0); shape_ptr = &shape_storage; } if (const Shape* intered_shape_ptr = TryInternShape(*shape_ptr)) { shape_ = intered_shape_ptr; } else { shape_ = std::make_unique<Shape>(*shape_ptr); } } void Literal::SetPiece(const Shape& shape, Piece* piece, bool allocate_arrays, ArrayValueState leaf_array_value_state) { if (shape.IsTuple()) { for (const Shape& subshape : shape.tuple_shapes()) { Piece child_piece; child_piece.set_subshape(&subshape); SetPiece(subshape, &child_piece, allocate_arrays, leaf_array_value_state); piece->emplace_back(std::move(child_piece)); } } else if (shape.IsArray()) { DCHECK(LayoutUtil::IsDenseArray(shape)) << "literal array storage is currently only supported for dense " "arrays: " << shape; piece->set_array_value_state(leaf_array_value_state); if (leaf_array_value_state == LiteralBase::ArrayValueState::kKnown && allocate_arrays) { piece->AllocateBuffers(); } } } Literal::Literal(const Shape& shape, bool allocate_arrays, ArrayValueState leaf_array_value_state) : MutableLiteralBase() { SetShape(shape); CHECK(leaf_array_value_state != ArrayValueState::kKnown || LayoutUtil::HasLayout(*shape_)); root_piece_.set_subshape(shape_.get()); CHECK(&root_piece_.subshape() == shape_.get()); SetPiece(*shape_, &root_piece_, allocate_arrays, leaf_array_value_state); } Literal::~Literal() { DeallocateBuffers(); } void Literal::DeallocateBuffers() { root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { piece->DeallocateBuffers(); }); } Literal::Literal(Literal&& other) : MutableLiteralBase() { *this = std::move(other); } Literal& Literal::operator=(Literal&& other) { DCHECK(&other.root_piece_.subshape() == other.shape_.get()); using std::swap; swap(shape_, other.shape_); swap(root_piece_, other.root_piece_); DCHECK(&root_piece_.subshape() == shape_.get()); return *this; } Literal LiteralBase::CreateFromShape(const Shape& shape) { Literal literal(shape); literal.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (piece->subshape().IsArray()) { memset(piece->untyped_data(), 0, piece->size_bytes_dense()); } }); return literal; } [&](const ShapeIndex& index, Piece* piece) { if (piece->subshape().IsArray()) { memset(piece->untyped_data(), 0, piece->size_bytes_dense()); } }); Literal LiteralBase::CreateFromShapeWithUnknownLeafArrays(const Shape& shape) { Literal literal(shape, /*allocate_arrays=*/false, ArrayValueState::kUnknown); return literal; } Literal LiteralBase::CreateFromShapeWithUndeterminedLeafArrays( const Shape& shape) { Literal literal(shape, /*allocate_arrays=*/false, ArrayValueState::kUndetermined); return literal; } int32_t LiteralBase::GetDynamicSize(int64_t dim_index) const { return GetDynamicSize(dim_index, {}); } int32_t LiteralBase::GetDynamicSize(int64_t dim_index, const ShapeIndex& shape_index) const { return piece(shape_index).GetDynamicSize(dim_index); } std::optional<int64_t> LiteralBase::GetFirstInteger() const { if (!primitive_util::IsIntegralType(shape().element_type())) { return std::nullopt; } return primitive_util::IntegralTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, void LiteralBase::BuildPieceSubtree(const Shape& shape, Piece* piece) { CHECK(shape.IsTuple()); for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); Piece child_piece; child_piece.set_subshape(&subshape); if (subshape.IsTuple()) { BuildPieceSubtree(subshape, &child_piece); } piece->emplace_back(std::move(child_piece)); } } absl::Status LiteralBase::SerializeToString(std::string* output) const { ShapeProto shape_proto = shape().ToProto(); TF_ASSIGN_OR_RETURN(int64_t size, ShapeUtil::SerializedSizeWithProto(shape(), shape_proto)); output->resize(size); return SerializeWithShapeProto(shape_proto, output->data()); } absl::StatusOr<std::string> LiteralBase::SerializeAsString() const { std::string result; TF_RETURN_IF_ERROR(SerializeToString(&result)); return std::move(result); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { void MutableLiteralBase::CopyElementFrom(const LiteralSlice& src_literal, absl::Span<const int64_t> src_index, absl::Span<const int64_t> dest_index) { DCHECK(LayoutUtil::IsDenseArray(shape())); DCHECK_EQ(shape().element_type(), src_literal.shape().element_type()); const int64_t src_linear_index = IndexUtil::MultidimensionalIndexToLinearIndex(src_literal.shape(), src_index); const int64_t dest_linear_index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), dest_index); const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); char* dest_address = static_cast<char*>(untyped_data()) + dest_linear_index * primitive_size; const char* source_address = static_cast<const char*>(src_literal.untyped_data()) + src_linear_index * primitive_size; if (dest_address != source_address) { memcpy(dest_address, source_address, primitive_size); } } /* static */ absl::StatusOr<Literal> MutableLiteralBase::CreateFromProto( const LiteralProto& proto, bool prohibit_empty_literal) { if (!proto.has_shape()) { return InvalidArgument("LiteralProto has no shape"); } Shape shape(proto.shape()); if (ShapeUtil::HasPrimitiveType(shape, OPAQUE_TYPE)) { return InvalidArgument( "Literal shape cannot include OPAQUE_TYPE sub-shape"); } if (!LayoutUtil::HasLayout(shape)) { return InvalidArgument("LiteralProto has no layout"); } if (LayoutUtil::IsSparseArray(shape)) { return Unimplemented("Sparse literals are not supported"); } TF_RETURN_IF_ERROR(ShapeUtil::ValidateShapeWithOptionalLayout(shape)); Literal literal(shape); TF_RETURN_IF_ERROR(literal.root_piece_.ForEachMutableSubpieceWithStatus( [&](const ShapeIndex& index, Piece* piece) -> absl::Status { const LiteralProto* proto_element = &proto; for (int64_t i : index) { CHECK(i < proto_element->tuple_literals_size()); proto_element = &proto_element->tuple_literals(i); } if (piece->subshape().IsTuple()) { if (proto_element->tuple_literals_size() != ShapeUtil::TupleElementCount(piece->subshape())) { return InvalidArgument( "Expected %d tuple elements in LiteralProto, has %d", ShapeUtil::TupleElementCount(piece->subshape()), proto_element->tuple_literals_size()); } return absl::OkStatus(); } if (piece->subshape().element_type() == TOKEN) { return absl::OkStatus(); } CHECK(piece->subshape().IsArray()); // When prohibit_empty_literal is false (allowing literal with no // values), only copy from proto if the literal proto has values. This // mode is used for a learned cost model. if (prohibit_empty_literal || LiteralProtoHasValues(*proto_element)) { TF_RETURN_IF_ERROR(piece->CopyFromProto(*proto_element)); } return absl::OkStatus(); })); return std::move(literal); } TF_RETURN_IF_ERROR(literal.root_piece_.ForEachMutableSubpieceWithStatus( Literal Literal::SubLiteral(ShapeIndexView shape_index) { if (!shape_index.empty()) { auto decomposed = this->DecomposeTuple(); return decomposed.at(shape_index.front()) .SubLiteral(shape_index.subspan(1)); } else { return std::move(*this); } } std::vector<Literal> Literal::DecomposeTuple() { CHECK(shape().IsTuple()); std::vector<Literal> elements; const auto tuple_element_count = ShapeUtil::TupleElementCount(shape()); elements.reserve(tuple_element_count); for (int i = 0; i < tuple_element_count; ++i) { elements.push_back(Literal(ShapeUtil::GetSubshape(shape(), {i}), /*allocate_arrays=*/false)); Literal& element = elements.back(); element.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* dest_piece) { if (dest_piece->subshape().IsTuple()) { return; } ShapeIndex src_index = {i}; for (int64_t j : index) { src_index.push_back(j); } Piece& src_piece = piece(src_index); // Move the respective buffer over to the element Literal. dest_piece->MoveDataFrom(src_piece); }); } // Set this literal to be nil-shaped. *this = Literal(); return elements; } [&](const ShapeIndex& index, Piece* dest_piece) { if (dest_piece->subshape().IsTuple()) { return; } ShapeIndex src_index = {i}; for (int64_t j : index) { src_index.push_back(j); } Piece& src_piece = piece(src_index); // Move the respective buffer over to the element Literal. dest_piece->MoveDataFrom(src_piece); }); void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } int32_t LiteralBase::Piece::GetDynamicSize(int64_t dim_index) const { CHECK(LayoutUtil::IsDenseArray(subshape())); if (!subshape_->is_dynamic_dimension(dim_index)) { // This is a static dimension, return size. return subshape_->dimensions(dim_index); } return dynamic_size_buffer()[dim_index]; } void LiteralBase::Piece::SetDynamicSize(int64_t dim_index, int32_t size) { CHECK(LayoutUtil::IsDenseArray(subshape())); CHECK(subshape_->is_dynamic_dimension(dim_index)); dynamic_size_buffer()[dim_index] = size; } void LiteralBase::Piece::AllocateBuffers() { const int64_t bytes = total_bytes_dense(); if (bytes > kMaxInlinedBytes) { CHECK_EQ(buffer(), nullptr); rep_.emplace<DenseRep>(); set_buffer( static_cast<char*>(tsl::port::AlignedMalloc(bytes, kMinimumAlignment))); } else { rep_.emplace<DenseInlinedRep>(); } } void LiteralBase::Piece::DeallocateBuffers() { if (auto* array_rep = GetDenseRep()) { tsl::port::AlignedFree(array_rep->data); rep_.emplace<Uninitialized>(); } } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } absl::Status LiteralBase::Piece::CopyFrom(const LiteralBase::Piece& src, bool only_dynamic_bound) { CHECK(subshape_ != nullptr); CHECK(src.subshape_ != nullptr); CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK(LayoutUtil::IsDenseArray(src.subshape())) << __func__ << " is only supported for dense arrays: " << src.subshape(); if (!only_dynamic_bound) { CHECK(ShapeUtil::Compatible(subshape(), src.subshape())); } if (src.array_value_state_ == ArrayValueState::kUnknown || src.array_value_state_ == ArrayValueState::kUndetermined) { if (array_value_state_ == ArrayValueState::kKnown) { DeallocateBuffers(); } array_value_state_ = src.array_value_state_; return absl::OkStatus(); } else { CHECK(src.array_value_state_ == ArrayValueState::kKnown); if (array_value_state_ == ArrayValueState::kUndetermined || array_value_state_ == ArrayValueState::kUnknown) { AllocateBuffers(); } array_value_state_ = src.array_value_state_; } if (ShapeUtil::Equal(subshape(), src.subshape())) { // If the layouts are equal it's faster just to memcpy. memcpy(buffer(), src.buffer(), src.size_bytes_dense()); } else { std::vector<int64_t> origin(subshape().rank(), 0); primitive_util::ArrayTypeSwitch<void>( [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, subshape().element_type()); } DCHECK_EQ(dynamic_size_buffer_bytes(), src.dynamic_size_buffer_bytes()); if (subshape().is_dynamic() && src.subshape().is_dynamic()) { memcpy(dynamic_size_buffer(), src.dynamic_size_buffer(), src.dynamic_size_buffer_bytes()); } return absl::OkStatus(); } [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, void MutableLiteralBase::SetDynamicSize(int64_t dim_index, int32_t size) { return SetDynamicSize(dim_index, {}, size); } void MutableLiteralBase::SetDynamicSize(int64_t dim_index, const ShapeIndex& shape_index, int32_t size) { Shape* subshape = ShapeUtil::GetMutableSubshape(mutable_shape_do_not_use(), shape_index); CHECK(LayoutUtil::IsDenseArray(*subshape)) << __func__ << " is only supported for dense arrays: " << *subshape; CHECK_GE(subshape->dimensions(dim_index), size); subshape->set_dynamic_dimension(dim_index, true); CHECK_EQ(&piece(shape_index).subshape(), subshape); piece(shape_index).SetDynamicSize(dim_index, size); } absl::Status MutableLiteralBase::CopyFrom(const LiteralSlice& src_literal, const ShapeIndex& dest_shape_index, const ShapeIndex& src_shape_index, bool only_dynamic_bound) { const Shape& dest_subshape = ShapeUtil::GetSubshape(shape(), dest_shape_index); const Shape& src_subshape = ShapeUtil::GetSubshape(src_literal.shape(), src_shape_index); if (only_dynamic_bound) { auto& bound_shape = dest_subshape.is_static() ? src_subshape : dest_subshape; auto& compact_shape = dest_subshape.is_static() ? dest_subshape : src_subshape; CHECK(ShapeUtil::DynamicShapeIsCompatible(compact_shape, bound_shape)) << compact_shape.ToString() << " vs " << bound_shape.ToString(); } else { if (!ShapeUtil::Compatible(dest_subshape, src_subshape)) { return InvalidArgument( "Destination subshape incompatible with source subshape: %s vs %s", ShapeUtil::HumanString(dest_subshape), ShapeUtil::HumanString(src_subshape)); } } return mutable_root_piece().ForEachMutableSubpieceWithStatus( [&](const ShapeIndex& index, Piece* piece) { if (!piece->subshape().IsArray()) { return absl::OkStatus(); } // Determine if this index is in the part of this literal that we want // to copy over from src_literal. bool in_subtree_to_copy = true; for (int i = 0; i < dest_shape_index.size(); ++i) { if (index[i] != dest_shape_index[i]) { in_subtree_to_copy = false; break; } } if (!in_subtree_to_copy) { return absl::OkStatus(); } // Construct the index of the corresponding piece in the source literal. ShapeIndex src_piece_index = src_shape_index; for (int64_t i = dest_shape_index.size(), end = index.size(); i < end; ++i) { src_piece_index.push_back(index[i]); } TF_RETURN_IF_ERROR( piece->CopyFrom(src_literal.piece(src_piece_index), /*only_dynamic_bound=*/only_dynamic_bound)); return absl::OkStatus(); }); } [&](const ShapeIndex& index, Piece* piece) { if (!piece->subshape().IsArray()) { return absl::OkStatus(); } // Determine if this index is in the part of this literal that we want // to copy over from src_literal. bool in_subtree_to_copy = true; for (int i = 0; i < dest_shape_index.size(); ++i) { if (index[i] != dest_shape_index[i]) { in_subtree_to_copy = false; break; } } if (!in_subtree_to_copy) { return absl::OkStatus(); } // Construct the index of the corresponding piece in the source literal. ShapeIndex src_piece_index = src_shape_index; for (int64_t i = dest_shape_index.size(), end = index.size(); i < end; ++i) { src_piece_index.push_back(index[i]); } TF_RETURN_IF_ERROR( piece->CopyFrom(src_literal.piece(src_piece_index), /*only_dynamic_bound=*/only_dynamic_bound)); return absl::OkStatus(); }); absl::Status Literal::MoveFrom(Literal&& src_literal, const ShapeIndex& dest_shape_index) { const Shape& dest_subshape = ShapeUtil::GetSubshape(shape(), dest_shape_index); if (!ShapeUtil::Equal(dest_subshape, src_literal.shape())) { return InvalidArgument( "Destination subshape not equal to source shape: %s vs %s", ShapeUtil::HumanString(dest_subshape), ShapeUtil::HumanString(src_literal.shape())); } src_literal.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& src_index, Piece* src_piece) { if (!src_piece->subshape().IsArray()) { return; } ShapeIndex dest_index = dest_shape_index; for (int64_t i : src_index) { dest_index.push_back(i); } Piece& dest_piece = piece(dest_index); dest_piece.DeallocateBuffers(); dest_piece.MoveDataFrom(*src_piece); }); src_literal.shape_ = MaybeOwningShapePtr(&NilShape()); src_literal.root_piece_ = Piece(); src_literal.root_piece_.set_subshape(src_literal.shape_.get()); return absl::OkStatus(); } [&](const ShapeIndex& src_index, Piece* src_piece) { if (!src_piece->subshape().IsArray()) { return; } ShapeIndex dest_index = dest_shape_index; for (int64_t i : src_index) { dest_index.push_back(i); } Piece& dest_piece = piece(dest_index); dest_piece.DeallocateBuffers(); dest_piece.MoveDataFrom(*src_piece); }); absl::Status MutableLiteralBase::CopySliceFrom( const LiteralSlice& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << shape(); TF_RET_CHECK(LayoutUtil::IsDenseArray(src_literal.shape())) << src_literal.shape(); TF_RET_CHECK(ShapeUtil::SameElementType(src_literal.shape(), shape())); TF_RET_CHECK(src_literal.shape().rank() == src_base.size()); TF_RET_CHECK(shape().rank() == dest_base.size()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, void MutableLiteralBase::PopulateR1(const tsl::core::Bitmap& values) { CHECK(shape().IsArray()); CHECK_EQ(shape().rank(), 1); CHECK_EQ(element_count(), values.bits()); CHECK_EQ(shape().element_type(), PRED); for (int64_t i = 0; i < static_cast<int64_t>(values.bits()); ++i) { Set({i}, values.get(i)); } } void MutableLiteralBase::PopulateInplaceInternal( absl::FunctionRef<void(void*, absl::Span<const int64_t>, int)> populator, bool parallel) { const Shape& this_shape = shape(); const int64_t rank = this_shape.rank(); DCHECK(LayoutUtil::IsDenseArray(this_shape)); char* const dest_base = static_cast<char*>(untyped_data()); if (rank > 0) { StrideConfig stride_config(this_shape, this_shape, this_shape.dimensions()); const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); const int64_t num_elements = ShapeUtil::ElementsIn(shape()); // If we are rank-1 and we are `parallel`, it is better to use a smaller // `step` than what `StrideConfig` does: stick the entire dimension in the // inner-most loop. if (parallel && this_shape.rank() == 1) { const int64_t thread_count = ShapeUtil::GetForEachIndexParallelThreadCount(); // Let's just divide up the array into small amounts per thread. stride_config.dest_stride = stride_config.minor_loop_size = num_elements > 32 ? std::max<int64_t>(num_elements / thread_count, 1) : num_elements; stride_config.step = {stride_config.minor_loop_size}; } auto init_function = [&](absl::Span<const int64_t> indexes, int thread_id) -> absl::StatusOr<bool> { const int64_t index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), indexes); DimensionVector minor_scan_indexes(rank, 0); std::copy(indexes.begin(), indexes.end(), minor_scan_indexes.begin()); char* dest_ptr = dest_base + index * primitive_size; char* const dest_end = dest_base + // This handles the case where minor_loop_size does not evenly divide // the most minor dimension. std::min(index + stride_config.minor_loop_size, num_elements) * primitive_size; while (dest_ptr < dest_end) { populator(dest_ptr, minor_scan_indexes, thread_id); ++minor_scan_indexes[stride_config.minor_dimension]; dest_ptr += primitive_size; } return true; }; if (parallel) { ShapeUtil::ForEachIndexParallel(this_shape, stride_config.base, stride_config.dimensions, stride_config.step, init_function); } else { ShapeUtil::ForEachIndex( this_shape, stride_config.base, stride_config.dimensions, stride_config.step, [&init_function]( absl::Span<const int64_t> indexes) -> absl::StatusOr<bool> { auto result_ignored = init_function(indexes, /*thread_id=*/-1); return true; }); } } else { // For scalars. populator(dest_base, {}, /*thread_id=*/-1); } } auto init_function = [&](absl::Span<const int64_t> indexes, int thread_id) -> absl::StatusOr<bool> { const int64_t index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), indexes); DimensionVector minor_scan_indexes(rank, 0); std::copy(indexes.begin(), indexes.end(), minor_scan_indexes.begin()); char* dest_ptr = dest_base + index * primitive_size; char* const dest_end = dest_base + // This handles the case where minor_loop_size does not evenly divide // the most minor dimension. std::min(index + stride_config.minor_loop_size, num_elements) * primitive_size; while (dest_ptr < dest_end) { populator(dest_ptr, minor_scan_indexes, thread_id); ++minor_scan_indexes[stride_config.minor_dimension]; dest_ptr += primitive_size; } return true; }; [&init_function]( absl::Span<const int64_t> indexes) -> absl::StatusOr<bool> { auto result_ignored = init_function(indexes, /*thread_id=*/-1); return true; }); absl::Status MutableLiteralBase::PopulateInplace( absl::FunctionRef<void(void*, absl::Span<const int64_t>)> populator) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); PopulateInplaceInternal( [&](void* dest, absl::Span<const int64_t> indexes, int /*thread_id*/) { return populator(dest, indexes); }, /*parallel=*/false); return absl::OkStatus(); } absl::Status MutableLiteralBase::PopulateInplaceParallel( absl::FunctionRef<void(void*, absl::Span<const int64_t>, int)> populator) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); PopulateInplaceInternal(populator, /*parallel=*/element_count() > 32); return absl::OkStatus(); } Literal LiteralBase::Relayout(const Layout& new_layout, const ShapeIndex& shape_index) const { // Create new shape with 'new_layout' set at the given shape index. Shape new_shape = shape(); Shape* subshape = ShapeUtil::GetMutableSubshape(&new_shape, shape_index); TF_CHECK_OK(LayoutUtil::ValidateLayoutForShape(new_layout, *subshape)); *subshape->mutable_layout() = new_layout; // LINT.IfChange // s4 literals are stored in uint8_t/int8_t, therefore element_size_in_bits // must be removed. if (subshape->layout().element_size_in_bits() == 4) { subshape->mutable_layout()->set_element_size_in_bits(0); } // LINT.ThenChange(//tensorflow/compiler/xla/types.h) Literal result(new_shape); TF_CHECK_OK(result.CopyFrom(*this)); return result; } Literal LiteralBase::Relayout(const Shape& shape_with_layout) const { CHECK(ShapeUtil::Compatible(shape_with_layout, shape())) << "Given shape_with_layout " << ShapeUtil::HumanString(shape_with_layout) << " not compatible with literal shape " << ShapeUtil::HumanString(shape()); Literal result = CreateFromShape(shape_with_layout); ShapeUtil::ForEachSubshape( result.shape(), [this, &result](const Shape& subshape, const ShapeIndex& index) { if (subshape.IsArray()) { TF_CHECK_OK(result.CopyFrom(*this, /*dest_shape_index=*/index, /*src_shape_index=*/index)); } }); return result; } [this, &result](const Shape& subshape, const ShapeIndex& index) { if (subshape.IsArray()) { TF_CHECK_OK(result.CopyFrom(*this, /*dest_shape_index=*/index, /*src_shape_index=*/index)); } }); Literal LiteralBase::ToBoundedDynamic(const Shape& bounded_shape) const { CHECK(bounded_shape.is_dynamic()); Literal result(bounded_shape); ShapeUtil::ForEachSubshape( shape(), [&](const Shape& subshape, const ShapeIndex& index) { if (!subshape.IsArray()) { return; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (bounded_shape.is_dynamic_dimension(i)) { result.SetDynamicSize(i, subshape.dimensions(i)); } } }); TF_CHECK_OK(result.CopyFrom(*this, {}, {}, /*only_dynamic_bound=*/true)); return result; } shape(), [&](const Shape& subshape, const ShapeIndex& index) { if (!subshape.IsArray()) { return; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (bounded_shape.is_dynamic_dimension(i)) { result.SetDynamicSize(i, subshape.dimensions(i)); } } }); Literal LiteralBase::ToStatic() const { // Create new shape with 'new_layout' set at the given shape index. Shape new_shape = shape(); ShapeUtil::ForEachMutableSubshape( &new_shape, [this](Shape* subshape, const ShapeIndex& index) { if (!subshape->IsArray()) { return; } for (int64_t i = 0; i < subshape->rank(); ++i) { // GetDynamicSize has a 32-bit return type and may truncate static // dimensions, so make sure to skip. if (!subshape->is_dynamic_dimension(i)) continue; subshape->set_dynamic_dimension(i, false); subshape->set_dimensions(i, GetDynamicSize(i, index)); } }); Literal result(new_shape); TF_CHECK_OK(result.CopyFrom(*this, {}, {}, /*only_dynamic_bound=*/true)); return result; } &new_shape, [this](Shape* subshape, const ShapeIndex& index) { if (!subshape->IsArray()) { return; } for (int64_t i = 0; i < subshape->rank(); ++i) { // GetDynamicSize has a 32-bit return type and may truncate static // dimensions, so make sure to skip. if (!subshape->is_dynamic_dimension(i)) continue; subshape->set_dynamic_dimension(i, false); subshape->set_dimensions(i, GetDynamicSize(i, index)); } }); absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { absl::StatusOr<Literal> LiteralBase::Broadcast( const Shape& result_shape, absl::Span<const int64_t> dimensions) const { const LiteralBase& src = *this; const Shape& src_shape = shape(); if (!src_shape.IsArray()) { return InvalidArgument("Broadcast only supports arrays."); } const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(src_shape.element_type()); switch (primitive_size) { case 0: return BroadcastHelper<0>(src, src_shape, result_shape, dimensions); case 1: return BroadcastHelper<1>(src, src_shape, result_shape, dimensions); case 2: return BroadcastHelper<2>(src, src_shape, result_shape, dimensions); case 4: return BroadcastHelper<4>(src, src_shape, result_shape, dimensions); case 8: return BroadcastHelper<8>(src, src_shape, result_shape, dimensions); case 16: return BroadcastHelper<16>(src, src_shape, result_shape, dimensions); default: LOG(FATAL) << "Unhandled primitive size " << primitive_size; return InvalidArgument("Unhandled primitive size"); break; } } absl::StatusOr<Literal> LiteralBase::Reshape( absl::Span<const int64_t> dimensions) const { if (!LayoutUtil::IsDenseArray(shape())) { return InvalidArgument("Reshape is only supported for dense arrays."); } if (shape().is_dynamic()) { // TODO(b/243182930): We should consider supporting dynamic reshape. return Unimplemented("Dynamic reshape is not implemented."); } Literal output; if (!LayoutUtil::IsMonotonicWithDim0Major(shape().layout())) { output = Relayout(LayoutUtil::GetDefaultLayoutForRank(shape().rank())); } else { output = Clone(); } // Because the layout is monotonic, we can simply reuse the same sequence of // values without changing their order. *output.mutable_shape_do_not_use() = ShapeUtil::MakeShape(shape().element_type(), dimensions); int64_t elements_before = ShapeUtil::ElementsIn(shape()); int64_t elements_after = ShapeUtil::ElementsIn(output.shape()); if (elements_before != elements_after) { return InvalidArgument( "Shapes before and after Literal::Reshape have different numbers " "of elements: %s vs %s.", ShapeUtil::HumanString(shape()), ShapeUtil::HumanString(output.shape())); } return std::move(output); } Literal LiteralBase::Transpose(absl::Span<const int64_t> permutation) const { CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); CHECK(shape().rank() == permutation.size() && IsPermutation(permutation)) << "Given permutation is not a permutation of dimension numbers"; // To transpose the array, we just permute the dimensions and layout, and // do a straight memory copy of the raw data set. // This is considerably faster than iterating over every array element using // the EachCell<>() and Set<>() APIs. Shape permuted_shape = ShapeUtil::PermuteDimensions(permutation, shape()); // Replace the layout with one affine to this shape, such that a // transpose operation can be performed by leaving the flat values // representation intact. // For example, consider the shape F32[11,8]{1,0} under a {1,0} permutation. // The shape with affine layout resulting from that operation will be // F32[8,11]{0,1}, since it leaves the original most minor (the 8 sized), the // most minor. // // Essentially, given MinMaj(Di) the position of the Di dimension within the // minor to major vector, and given T(Di) the index that the original Di // dimension has within the transposed array, a layout is affine if // MinMaj(Di) == TMinMaj(T(Di)), with TMinMaj() being the minor to major // vector of the affine layout. std::vector<int64_t> inverse_permutation = InversePermutation(permutation); CHECK(LayoutUtil::IsDenseArray(permuted_shape)); Layout* layout = permuted_shape.mutable_layout(); layout->clear_minor_to_major(); for (auto index : LayoutUtil::MinorToMajor(shape())) { layout->add_minor_to_major(inverse_permutation[index]); } Literal new_literal(permuted_shape); if (shape().is_dynamic()) { for (int64_t i = 0; i < shape().rank(); i++) { if (shape().is_dynamic_dimension(i)) { // Set the dynamic size of any dynamic dimension in the transposed // literal. new_literal.SetDynamicSize(inverse_permutation[i], GetDynamicSize(i)); } } } DCHECK_EQ(ShapeUtil::ByteSizeOf(new_literal.shape()), ShapeUtil::ByteSizeOf(shape())); std::memcpy(new_literal.untyped_data(), untyped_data(), size_bytes()); return new_literal; } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( Literal LiteralBase::Slice(absl::Span<const int64_t> start_indices, absl::Span<const int64_t> limit_indices) const { CHECK(shape().IsArray()) << "tuple is not supported for slice"; DimensionVector result_dimensions; for (int64_t dnum = 0; dnum < shape().rank(); ++dnum) { CHECK_GE(start_indices[dnum], 0); CHECK_LE(limit_indices[dnum], shape().dimensions(dnum)) << "dnum = " << dnum; int64_t dimension = limit_indices[dnum] - start_indices[dnum]; CHECK_GE(dimension, 0) << "dnum = " << dnum; result_dimensions.push_back(dimension); } auto result_shape = ShapeUtil::MakeShapeWithDenseLayout( shape().element_type(), result_dimensions, LayoutUtil::MinorToMajor(shape())); ShapeUtil::CopyDynamicDimensions(&result_shape, shape()); Literal result_literal(result_shape); primitive_util::ArrayTypeSwitch<void>( [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; return SliceInternal<NativeT>(*this, start_indices, result_literal); }, result_shape.element_type()); return result_literal; } Literal LiteralBase::Clone() const { Literal result(shape()); TF_CHECK_OK(result.CopyFrom(*this)); return result; } std::unique_ptr<Literal> LiteralBase::CloneToUnique() const { auto result = std::make_unique<Literal>(shape()); TF_CHECK_OK(result->CopyFrom(*this)); return result; } bool LiteralBase::IsDetermined(const ShapeIndex& shape_index) const { return piece(shape_index).IsDetermined(); } bool LiteralBase::IsKnown(const ShapeIndex& shape_index) const { return piece(shape_index).IsKnown(); } std::string LiteralBase::GetAsString(absl::Span<const int64_t> multi_index, const ShapeIndex& shape_index) const { const Shape& subshape = ShapeUtil::GetSubshape(shape(), shape_index); CHECK(LayoutUtil::IsDenseArray(subshape)); return primitive_util::ArrayTypeSwitch<std::string>( [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, subshape.element_type()); } [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, std::optional<int64_t> LiteralBase::GetIntegralAsS64( absl::Span<const int64_t> multi_index) const { CHECK(LayoutUtil::IsDenseArray(shape())); return primitive_util::PrimitiveTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, std::optional<double> LiteralBase::GetAsDouble( absl::Span<const int64_t> multi_index) const { const Shape& s = shape(); CHECK(LayoutUtil::IsDenseArray(s)); return primitive_util::PrimitiveTypeSwitch<std::optional<double>>( [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, s.element_type()); } [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, std::optional<double> LiteralBase::GetSumAsDouble( absl::Span<const int64_t> linear_indices) const { const Shape& s = shape(); CHECK(LayoutUtil::IsDenseArray(s)); if (!primitive_util::IsFloatingPointType(s.element_type())) { return std::nullopt; } return primitive_util::FloatingPointTypeSwitch<double>( [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, s.element_type()); } [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, std::optional<complex128> LiteralBase::GetAsComplex128( absl::Span<const int64_t> multi_index) const { return primitive_util::PrimitiveTypeSwitch<std::optional<complex128>>( [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, absl::Status MutableLiteralBase::SetIntegralAsS64( absl::Span<const int64_t> multi_index, int64_t value) { CHECK(LayoutUtil::IsDenseArray(shape())); return primitive_util::PrimitiveTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, absl::Status MutableLiteralBase::SetFromDouble( absl::Span<const int64_t> multi_index, double value) { CHECK(LayoutUtil::IsDenseArray(shape())); if (!primitive_util::IsFloatingPointType(shape().element_type())) { return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); } primitive_util::FloatingPointTypeSwitch<void>( [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, shape().element_type()); return absl::OkStatus(); } [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, void PrintShape(bool print_layout, const Shape& shape, Printer* printer) { if (print_layout) { ShapeUtil::PrintHumanStringWithLayout(printer, shape); } else { ShapeUtil::PrintHumanString(printer, shape); } } void TuplePrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); printer->Append(oneline ? "( " : "(\n"); for (int i = 0; i < ShapeUtil::TupleElementCount(subshape); ++i) { ShapeIndex element_index = shape_index; element_index.push_back(i); if (i > 0) printer->Append(oneline ? ", " : ",\n"); PrintHelper(literal, element_index, print_shape, print_layout, oneline, printer); } printer->Append(oneline ? " )" : "\n)"); } void DenseArrayPrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); int64_t rank = subshape.rank(); const absl::string_view linebreak = oneline ? " " : "\n"; std::function<void(absl::Span<const int64_t> dimensions, std::vector<int64_t>*)> print_recursive = [&](absl::Span<const int64_t> dimensions, std::vector<int64_t>* accum_indices) { // dimensions.size() decreases by 1 at each recursive call, // and accum_indices->size() increases by 1. // Their sum is equal to the rank of the tensor. CHECK_EQ(rank, dimensions.size() + accum_indices->size()); auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; if (dimensions.empty()) { // Display predicates as 0s and 1s so that the string is more dense. std::string elem; if (subshape.element_type() == PRED && rank > 0) { elem = literal.Get<bool>(*accum_indices, shape_index) ? "1" : "0"; } else { elem = literal.GetAsString(*accum_indices, shape_index); } printer->Append(elem); } else { printer->Append(brace_to_string("{")); for (int i = 0; i < dimensions[0]; ++i) { accum_indices->push_back(i); print_recursive(dimensions.subspan(1), accum_indices); accum_indices->pop_back(); if (i < dimensions[0] - 1) { printer->Append(","); printer->Append(dimensions.size() > 1 ? linebreak : " "); } } printer->Append(brace_to_string("}")); } }; if (print_shape) { PrintShape(print_layout, subshape, printer); if (subshape.is_dynamic()) { printer->Append("("); for (int64_t i = 0; i < subshape.dimensions_size(); ++i) { printer->Append(literal.GetDynamicSize(i, shape_index)); if (i < subshape.dimensions_size() - 1) { printer->Append(","); } } printer->Append(")"); } printer->Append(" "); } std::vector<int64_t> indices = {}; std::vector<int64_t> dimensions; dimensions.reserve(subshape.rank()); for (int64_t i = 0; i < subshape.rank(); ++i) { dimensions.push_back(literal.GetDynamicSize(i, shape_index)); } print_recursive(dimensions, &indices); } print_recursive = [&](absl::Span<const int64_t> dimensions, std::vector<int64_t>* accum_indices) { // dimensions.size() decreases by 1 at each recursive call, // and accum_indices->size() increases by 1. // Their sum is equal to the rank of the tensor. CHECK_EQ(rank, dimensions.size() + accum_indices->size()); auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; if (dimensions.empty()) { // Display predicates as 0s and 1s so that the string is more dense. std::string elem; if (subshape.element_type() == PRED && rank > 0) { elem = literal.Get<bool>(*accum_indices, shape_index) ? "1" : "0"; } else { elem = literal.GetAsString(*accum_indices, shape_index); } printer->Append(elem); } else { printer->Append(brace_to_string("{")); for (int i = 0; i < dimensions[0]; ++i) { accum_indices->push_back(i); print_recursive(dimensions.subspan(1), accum_indices); accum_indices->pop_back(); if (i < dimensions[0] - 1) { printer->Append(","); printer->Append(dimensions.size() > 1 ? linebreak : " "); } } printer->Append(brace_to_string("}")); } }; auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; void PrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); CHECK(LayoutUtil::HasLayout(literal.shape())); CHECK(LayoutUtil::HasLayout(subshape)); if (subshape.IsTuple()) { TuplePrintHelper(literal, shape_index, print_shape, print_layout, oneline, printer); } else if (subshape.IsToken()) { printer->Append("token"); } else { CHECK(LayoutUtil::IsDenseArray(subshape)); if (literal.IsKnown(shape_index)) { DenseArrayPrintHelper(literal, shape_index, print_shape, print_layout, oneline, printer); } else { PrintShape(print_layout, subshape, printer); printer->Append(" "); if (literal.IsDetermined(shape_index)) { printer->Append("unknown"); } else { printer->Append("undetermined"); } } } } void LiteralBase::Print(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/false, /*oneline=*/false, printer); } void LiteralBase::PrintOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/false, /*oneline=*/true, printer); } void LiteralBase::PrintWithoutShape(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/false, /*print_layout=*/false, /*oneline=*/false, printer); } void LiteralBase::PrintWithoutShapeOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/false, /*print_layout=*/false, /*oneline=*/true, printer); } void LiteralBase::PrintWithLayout(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/true, /*oneline=*/false, printer); } void LiteralBase::PrintWithLayoutOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/true, /*oneline=*/true, printer); } std::string LiteralBase::ToString() const { StringPrinter printer; Print(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringOneline() const { StringPrinter printer; PrintOneline(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithoutShape() const { StringPrinter printer; PrintWithoutShape(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithoutShapeOneline() const { StringPrinter printer; PrintWithoutShapeOneline(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithLayout() const { StringPrinter printer; PrintWithLayout(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithLayoutOneline() const { StringPrinter printer; PrintWithLayoutOneline(&printer); return std::move(printer).ToString(); } void LiteralBase::EachCellAsString( absl::FunctionRef<void(absl::Span<const int64_t> indices, const std::string& value)> per_cell) const { if (ShapeUtil::IsZeroElementArray(shape())) { return; } auto indices = IndexUtil::LinearIndexToMultidimensionalIndex( shape(), /*linear_index=*/0); do { per_cell(indices, GetAsString(indices)); } while (IndexUtil::BumpIndices(shape(), absl::MakeSpan(indices))); } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { absl::StatusOr<Literal> ConvertSwitch(const LiteralBase& literal, PrimitiveType primitive_dest_type) { TF_RET_CHECK(LayoutUtil::IsDenseArray(literal.shape())); if (literal.shape().element_type() == primitive_dest_type) { return literal.Clone(); } // Source Array type requirement is ensured by IsDenseArray before. if (!primitive_util::IsArrayType(primitive_dest_type) || !primitive_util::IsArrayType(literal.shape().element_type())) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(literal.shape().element_type()), PrimitiveType_Name(primitive_dest_type)); } // At this point, we know both src & dst are array types, while src is not // complex type, so we can allocate the result literal here to avoid // duplicating it N^2 times in the conversion implementation. Literal result( ShapeUtil::ChangeElementType(literal.shape(), primitive_dest_type)); TF_RETURN_IF_ERROR(primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { return ConvertIfDestTypeMatches<primitive_type_constant>(literal, result); }, literal.shape().element_type())); return result; } absl::StatusOr<Literal> LiteralBase::Convert( PrimitiveType primitive_dest_type) const { return ConvertSwitch(*this, primitive_dest_type); } absl::StatusOr<Literal> LiteralBase::BitcastConvert( const Shape& dest_shape) const { if (ShapeUtil::ByteSizeOf(dest_shape) != ShapeUtil::ByteSizeOf(shape())) { return InvalidArgument( "Can not bitcast-convert from shape %s to a shape of different size %s", shape().ToString(), dest_shape.ToString()); } if (dest_shape.IsTuple() || shape().IsTuple()) { return InvalidArgument( "bitcast-convert is not valid for tuple shapes %s->%s", shape().ToString(), dest_shape.ToString()); } if (shape().is_dynamic() || dest_shape.is_dynamic()) { return InvalidArgument( "bitcast-convert is not valid for dynamic shape %s->%s", shape().ToString(), dest_shape.ToString()); } Literal out(dest_shape); std::memcpy(out.root_piece_.buffer(), root_piece().buffer(), root_piece().size_bytes_dense()); // Perform the reshape on little endian encoding even on big endian machines. if constexpr (!kLittleEndian) { // Swap byte ordering as per the input data type. size_t input_elem_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); TF_RETURN_IF_ERROR(tsl::ByteSwapArray( const_cast<char*>(out.root_piece().buffer()), input_elem_size, out.root_piece().size_bytes_dense() / input_elem_size)); // Swap byte ordering as per the output data type. size_t output_elem_size = ShapeUtil::ByteSizeOfPrimitiveType(dest_shape.element_type()); TF_RETURN_IF_ERROR(tsl::ByteSwapArray( const_cast<char*>(out.root_piece().buffer()), output_elem_size, out.root_piece().size_bytes_dense() / output_elem_size)); } return out; } absl::StatusOr<Literal> LiteralBase::ConvertToShape( const Shape& dest_shape) const { if (!dest_shape.IsTuple()) { return Convert(dest_shape.element_type()); } std::vector<Literal> elements; const auto tuple_element_count = ShapeUtil::TupleElementCount(shape()); elements.reserve(tuple_element_count); for (int i = 0; i < tuple_element_count; ++i) { auto element = LiteralSlice(*this, {i}); TF_ASSIGN_OR_RETURN( auto new_element, element.ConvertToShape(ShapeUtil::GetSubshape(dest_shape, {i}))); elements.push_back(std::move(new_element)); } return MutableLiteralBase::MoveIntoTuple(absl::MakeSpan(elements)); } /* static */ Literal MutableLiteralBase::MoveIntoTuple( absl::Span<Literal> elements) { std::vector<const Shape*> element_shapes; element_shapes.reserve(elements.size()); for (const Literal& element : elements) { element_shapes.push_back(&element.shape()); } Literal literal(ShapeUtil::MakeTupleShapeWithPtrs(element_shapes), /*allocate_arrays=*/false); for (int i = 0, end = elements.size(); i < end; ++i) { TF_CHECK_OK( literal.MoveFrom(std::move(elements[i]), /*dest_shape_index=*/{i})); } return literal; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualDynamicSize( const LiteralBase::Piece& other) const { DCHECK(ShapeUtil::Compatible(subshape(), other.subshape())); if (subshape().is_static()) { return true; } for (int64_t i = 0; i < subshape().rank(); ++i) { if (GetDynamicSize(i) != other.GetDynamicSize(i)) { return false; } } return true; } bool LiteralBase::Piece::EqualElements(const LiteralBase::Piece& other) const { if (subshape().is_static() && ShapeUtil::Equal(subshape(), other.subshape()) && subshape().IsArray()) { CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(size_bytes_dense(), other.size_bytes_dense()); if (primitive_util::IsSubByteNonPredType(subshape().element_type())) { CHECK(!primitive_util::IsFloatingPointType(subshape().element_type())); auto one_array = buffer(); auto two_array = other.buffer(); const int bits_per_element = primitive_util::BitWidth(subshape().element_type()); const uint8_t mask = LsbMask<uint8_t>(bits_per_element); for (int64_t i = 0; i < size_bytes_dense(); ++i) { if ((one_array[i] & mask) != (two_array[i] & mask)) return false; } return true; } return memcmp(buffer(), other.buffer(), size_bytes_dense()) == 0; } std::vector<int64_t> multi_index; return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeSrcT = NativeTypeOf<primitive_type_constant>; return EqualElementsInternal<NativeSrcT>(other, &multi_index); }, subshape().element_type()); } bool LiteralBase::Equal(const LiteralBase& other, bool layout_sensitive) const { // Checking the structure of tuple literals. Checks for dense arrays are // performed below. if (!ShapeUtil::EqualStructure(shape(), other.shape())) { return false; } return root_piece().ForEachSubpieceWithBool([&](const ShapeIndex& index, const Piece& piece) { const Piece& other_piece = other.piece(index); const Shape& subshape = piece.subshape(); const Shape& other_subshape = other_piece.subshape(); if (subshape.element_type() != other_subshape.element_type()) { return false; } if (!piece.subshape().IsArray()) { return true; } if (subshape.rank() != other_subshape.rank()) { return false; } if (layout_sensitive && (subshape.layout() != other_subshape.layout())) { return false; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (piece.GetDynamicSize(i) != other_piece.GetDynamicSize(i)) { return false; } } if (!piece.EqualElements(other_piece)) { return false; } return true; }); } return root_piece().ForEachSubpieceWithBool([&](const ShapeIndex& index, const Piece& piece) { const Piece& other_piece = other.piece(index); const Shape& subshape = piece.subshape(); const Shape& other_subshape = other_piece.subshape(); if (subshape.element_type() != other_subshape.element_type()) { return false; } if (!piece.subshape().IsArray()) { return true; } if (subshape.rank() != other_subshape.rank()) { return false; } if (layout_sensitive && (subshape.layout() != other_subshape.layout())) { return false; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (piece.GetDynamicSize(i) != other_piece.GetDynamicSize(i)) { return false; } } if (!piece.EqualElements(other_piece)) { return false; } return true; }); static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(std::complex<T> a, std::complex<T> b) { return EqualIncludingNan(a.real(), b.real()) && EqualIncludingNan(a.imag(), b.imag()); } static bool EqualIncludingNan(std::complex<T> a, std::complex<T> b) { return EqualIncludingNan(a.real(), b.real()) && EqualIncludingNan(a.imag(), b.imag()); } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } bool Literal::Piece::IsAll(const Literal& scalar) const { CHECK(ShapeUtil::IsScalar(scalar.shape())) << scalar.shape().ToString(); if (!subshape().IsArray()) { return false; } CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(subshape().element_type(), scalar.shape().element_type()); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, subshape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, int64_t Literal::Piece::CountAll(const Literal& scalar) const { CHECK(ShapeUtil::IsScalar(scalar.shape())) << scalar.shape().ToString(); if (!subshape().IsArray()) { return 0; } CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(subshape().element_type(), scalar.shape().element_type()); return primitive_util::ArrayTypeSwitch<int64_t>( [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, subshape().element_type()); } [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { bool LiteralBase::IsAll(const Literal& scalar) const { return root_piece().IsAll(scalar); } bool LiteralBase::IsAll(int8_t value) const { if (!shape().IsArray()) { return false; } PrimitiveType ty = shape().element_type(); if (primitive_util::IsFloatingPointType(ty)) { return IsAllFloatImpl(value, /*round_value=*/false); } if (primitive_util::IsUnsignedIntegralType(ty) && value < 0) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllFloat(float value) const { return IsAllFloatImpl(value, /*round_value=*/true); } bool LiteralBase::IsAllFloatImpl(float value, bool round_value) const { PrimitiveType ty = shape().element_type(); if (!primitive_util::IsFloatingPointType(ty)) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::FloatingPointTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllComplex(complex64 value) const { PrimitiveType ty = shape().element_type(); if (!primitive_util::IsComplexType(ty)) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::ComplexTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllFirst() const { if (!shape().IsArray()) { return false; } // Empty shapes are not all the first element since there is no first element. if (ShapeUtil::IsZeroElementArray(shape())) { return false; } absl::InlinedVector<int64_t, 4> start_indices(/*n=*/shape().rank(), 0); absl::InlinedVector<int64_t, 4> end_indices(/*n=*/shape().rank(), 1); Literal first = Slice(start_indices, end_indices); return IsAll(first.Reshape({}).value()); } bool LiteralBase::IsR1Iota() const { if (!shape().IsArray()) { return false; } CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); if (shape().rank() != 1) { return false; } return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, shape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, std::optional<int64_t> LiteralBase::IsR1StridedIota() const { if (!shape().IsArray() || shape().rank() != 1) { return std::nullopt; } CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); const int64_t elements = ShapeUtil::ElementsIn(shape()); const PrimitiveType type = shape().element_type(); if (elements <= 1 || !primitive_util::IsIntegralType(type)) { return std::nullopt; } return primitive_util::IntegralTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, bool LiteralBase::IsZero(absl::Span<const int64_t> indices) const { CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, shape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void LiteralBase::Piece::set_array_value_state(ArrayValueState state) { array_value_state_ = state; } LiteralBase::ArrayValueState LiteralBase::Piece::get_array_value_state() const { return array_value_state_; } void LiteralBase::Piece::WriteToProto(LiteralProto* proto) const { *proto->mutable_shape() = subshape().ToProto(); switch (subshape().element_type()) { case PRED: CopyToRepeatedField(proto->mutable_preds(), data<bool>()); break; case U2: *proto->mutable_u2s() = std::string( reinterpret_cast<const char*>(data<u2>().data()), size_bytes_dense()); break; case U4: *proto->mutable_u4s() = std::string( reinterpret_cast<const char*>(data<u4>().data()), size_bytes_dense()); break; case U8: proto->set_u8s(static_cast<const unsigned char*>(data<uint8_t>().data()), element_count()); break; case U16: *proto->mutable_u16s() = std::string(reinterpret_cast<const char*>(data<uint16_t>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_u16s()); } break; case U32: CopyToRepeatedField(proto->mutable_u32s(), data<uint32_t>()); break; case U64: CopyToRepeatedField(proto->mutable_u64s(), data<uint64_t>()); break; case S2: *proto->mutable_s2s() = std::string( reinterpret_cast<const char*>(data<s2>().data()), size_bytes_dense()); break; case S4: *proto->mutable_s4s() = std::string( reinterpret_cast<const char*>(data<s4>().data()), size_bytes_dense()); break; case S8: proto->set_s8s(static_cast<const signed char*>(data<int8_t>().data()), element_count()); break; case S16: *proto->mutable_s16s() = std::string(reinterpret_cast<const char*>(data<int16_t>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_s16s()); } break; case S32: CopyToRepeatedField(proto->mutable_s32s(), data<int32_t>()); break; case S64: CopyToRepeatedField(proto->mutable_s64s(), data<int64_t>()); break; case F8E5M2: *proto->mutable_f8e5m2s() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e5m2>().data()), size_bytes_dense()); break; case F8E4M3FN: *proto->mutable_f8e4m3fns() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3fn>().data()), size_bytes_dense()); break; case F8E4M3B11FNUZ: *proto->mutable_f8e4m3b11fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3b11fnuz>().data()), size_bytes_dense()); break; case F8E5M2FNUZ: *proto->mutable_f8e5m2fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e5m2fnuz>().data()), size_bytes_dense()); break; case F8E4M3FNUZ: *proto->mutable_f8e4m3fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3fnuz>().data()), size_bytes_dense()); break; case F16: *proto->mutable_f16s() = std::string(reinterpret_cast<const char*>(data<half>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_f16s()); } break; case BF16: *proto->mutable_bf16s() = std::string(reinterpret_cast<const char*>(data<bfloat16>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_bf16s()); } break; case F32: CopyToRepeatedField(proto->mutable_f32s(), data<float>()); break; case F64: CopyToRepeatedField(proto->mutable_f64s(), data<double>()); break; case C64: for (complex64 value : data<complex64>()) { proto->add_c64s(value.real()); proto->add_c64s(value.imag()); } break; case C128: for (complex128 value : data<complex128>()) { proto->add_c128s(value.real()); proto->add_c128s(value.imag()); } break; case TUPLE: case TOKEN: // Nothing to do but assign the shape which is done above. return; default: // TODO(b/111551621): Support serializing more PrimitiveTypes. LOG(FATAL) << "Unhandled primitive type " << PrimitiveType_Name(subshape().element_type()); } } const void* LiteralBase::Piece::untyped_data() const { DCHECK(LayoutUtil::IsDenseArray(subshape())) << ShapeUtil::HumanString(subshape()); return buffer(); } void* LiteralBase::Piece::untyped_data() { DCHECK(LayoutUtil::IsDenseArray(subshape())) << ShapeUtil::HumanString(subshape()); return buffer(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status LiteralBase::Piece::CopyFromProto(const LiteralProto& proto) { // These conditions should have been checked in // MutableLiteralBase::CreateFromProto. TF_RET_CHECK(proto.has_shape()); Shape shape(proto.shape()); TF_RET_CHECK(LayoutUtil::HasLayout(shape)); TF_RET_CHECK(ShapeUtil::Equal(shape, subshape())); switch (subshape().element_type()) { case PRED: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<bool>(), proto.preds())); break; case S2: { const std::string& s(proto.s2s()); TF_RET_CHECK(data<s2>().size() * sizeof(s2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case S4: { const std::string& s(proto.s4s()); TF_RET_CHECK(data<s4>().size() * sizeof(s4) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case S8: { auto s8_data = data<int8_t>(); TF_RET_CHECK(proto.s8s().size() == s8_data.size()); std::copy(proto.s8s().begin(), proto.s8s().end(), s8_data.begin()); break; } case S16: { const std::string& s(proto.s16s()); TF_RET_CHECK(data<int16_t>().size() * sizeof(int16_t) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case S32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<int32_t>(), proto.s32s())); break; case S64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<int64_t>(), proto.s64s())); break; case U2: { const std::string& s(proto.u2s()); TF_RET_CHECK(data<u2>().size() * sizeof(u2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case U4: { const std::string& s(proto.u4s()); TF_RET_CHECK(data<u4>().size() * sizeof(u4) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case U8: { auto u8_data = data<uint8_t>(); TF_RET_CHECK(proto.u8s().size() == u8_data.size()); std::copy(proto.u8s().begin(), proto.u8s().end(), u8_data.begin()); break; } case U16: { const std::string& s(proto.u16s()); TF_RET_CHECK(data<uint16_t>().size() * sizeof(uint16_t) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case U32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<uint32_t>(), proto.u32s())); break; case U64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<uint64_t>(), proto.u64s())); break; case F8E5M2: { const std::string& s(proto.f8e5m2s()); TF_RET_CHECK(data<tsl::float8_e5m2>().size() * sizeof(tsl::float8_e5m2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3FN: { const std::string& s(proto.f8e4m3fns()); TF_RET_CHECK(data<tsl::float8_e4m3fn>().size() * sizeof(tsl::float8_e4m3fn) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3B11FNUZ: { const std::string& s(proto.f8e4m3b11fnuzs()); TF_RET_CHECK(data<tsl::float8_e4m3b11fnuz>().size() * sizeof(tsl::float8_e4m3b11fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E5M2FNUZ: { const std::string& s(proto.f8e5m2fnuzs()); TF_RET_CHECK(data<tsl::float8_e5m2fnuz>().size() * sizeof(tsl::float8_e5m2fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3FNUZ: { const std::string& s(proto.f8e4m3fnuzs()); TF_RET_CHECK(data<tsl::float8_e4m3fnuz>().size() * sizeof(tsl::float8_e4m3fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F16: { const std::string& s(proto.f16s()); TF_RET_CHECK(data<half>().size() * sizeof(half) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case BF16: { const std::string& s(proto.bf16s()); TF_RET_CHECK(data<bfloat16>().size() * sizeof(bfloat16) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case F32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<float>(), proto.f32s())); break; case F64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<double>(), proto.f64s())); break; case C64: { auto complex_data = data<complex64>(); TF_RET_CHECK(proto.c64s_size() == complex_data.size() * 2); for (int64_t i = 0; i < complex_data.size(); ++i) { complex_data[i] = complex64{proto.c64s(i * 2), proto.c64s(i * 2 + 1)}; } break; } case C128: { auto complex_data = data<complex128>(); const int64_t complex_data_size_doubled = complex_data.size() * 2; TF_RET_CHECK(proto.c128s_size() == complex_data_size_doubled); for (int64_t i = 0, end = complex_data.size(); i < end; ++i) { complex_data[i] = complex128{proto.c128s(i * 2), proto.c128s(i * 2 + 1)}; } break; } case TUPLE: return InvalidArgument("Should not be called on tuple shapes: %s", ShapeUtil::HumanString(subshape())); default: return InvalidArgument("Is called on unsupported shape: %s", ShapeUtil::HumanString(subshape())); } return absl::OkStatus(); } bool LiteralBase::Piece::IsKnown() const { if (array_value_state_ != ArrayValueState::kKnown) { return false; } if (subshape().IsTuple()) { bool are_all_leaf_arrays_known = true; ForEachSubpiece([&are_all_leaf_arrays_known](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_known &= piece.IsKnown(); }); return are_all_leaf_arrays_known; } return true; } ForEachSubpiece([&are_all_leaf_arrays_known](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_known &= piece.IsKnown(); }); bool LiteralBase::Piece::IsDetermined() const { if (array_value_state_ == ArrayValueState::kUndetermined) { return false; } if (subshape().IsTuple()) { bool are_all_leaf_arrays_determined = true; ForEachSubpiece([&are_all_leaf_arrays_determined](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_determined &= piece.IsDetermined(); }); return are_all_leaf_arrays_determined; } return true; } ForEachSubpiece([&are_all_leaf_arrays_determined](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_determined &= piece.IsDetermined(); }); LiteralProto LiteralBase::ToProto() const { LiteralProto proto; root_piece().ForEachSubpiece( [&](const ShapeIndex& index, const Piece& piece) { LiteralProto* proto_piece = &proto; for (int64_t i : index) { while (proto_piece->tuple_literals_size() <= i) { proto_piece->add_tuple_literals(); } proto_piece = proto_piece->mutable_tuple_literals(i); } piece.WriteToProto(proto_piece); }); return proto; } [&](const ShapeIndex& index, const Piece& piece) { LiteralProto* proto_piece = &proto; for (int64_t i : index) { while (proto_piece->tuple_literals_size() <= i) { proto_piece->add_tuple_literals(); } proto_piece = proto_piece->mutable_tuple_literals(i); } piece.WriteToProto(proto_piece); }); const void* LiteralBase::untyped_data(const ShapeIndex& shape_index) const { return piece(shape_index).untyped_data(); } void* MutableLiteralBase::untyped_data(const ShapeIndex& shape_index) { return piece(shape_index).untyped_data(); } int64_t LiteralBase::size_bytes(const ShapeIndex& shape_index) const { return piece(shape_index).size_bytes_dense(); } std::string LiteralBase::GetR1U8AsString() const { CHECK(shape().IsArray()); CHECK_EQ(shape().rank(), 1); CHECK_EQ(shape().element_type(), U8); return std::string(absl::bit_cast<const char*>(data<uint8_t>().data()), ShapeUtil::ElementsIn(shape())); } void MutableBorrowingLiteral::CopyPieceSubtree(const Shape& shape, const Piece* src_piece, Piece* dest_piece) { DCHECK(ShapeUtil::Equal(src_piece->subshape(), dest_piece->subshape())) << "src_piece has shape: " << ShapeUtil::HumanString(src_piece->subshape()) << "dest_piece has shape: " << ShapeUtil::HumanString(dest_piece->subshape()); dest_piece->set_array_value_state(src_piece->get_array_value_state()); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); Piece child_piece; child_piece.set_subshape(&subshape); CopyPieceSubtree(subshape, &src_piece->child(i), &child_piece); dest_piece->emplace_back(std::move(child_piece)); } } else if (shape.IsArray()) { dest_piece->set_buffer(const_cast<char*>(src_piece->buffer())); } } MutableLiteralBase::~MutableLiteralBase() = default; MutableBorrowingLiteral::MutableBorrowingLiteral( const MutableBorrowingLiteral& literal) : MutableLiteralBase() { shape_ = literal.shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.root_piece(), root_piece_); } MutableBorrowingLiteral& MutableBorrowingLiteral::operator=( const MutableBorrowingLiteral& literal) { shape_ = literal.shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.root_piece(), root_piece_); return *this; } MutableBorrowingLiteral::MutableBorrowingLiteral(MutableLiteralBase* literal) : MutableLiteralBase() { shape_ = literal->shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal->root_piece(), root_piece_); } MutableBorrowingLiteral::MutableBorrowingLiteral( MutableBorrowingLiteral literal, const ShapeIndex& view_root) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(literal.piece(view_root).subshape()); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.piece(view_root), root_piece_); } MutableBorrowingLiteral::MutableBorrowingLiteral(const char* src_buf_ptr, const Shape& shape) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(shape); CHECK(LayoutUtil::HasLayout(*shape_)); CHECK(!shape_->IsTuple()); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); root_piece_->set_buffer(const_cast<char*>(src_buf_ptr)); } MutableBorrowingLiteral::MutableBorrowingLiteral(absl::Span<char*> src_buf_ptrs, const Shape& shape) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(shape); if (!shape_->IsTuple()) { CHECK_EQ(src_buf_ptrs.size(), 1); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); root_piece_->set_buffer(const_cast<char*>(src_buf_ptrs[0])); } else { CHECK(!ShapeUtil::IsNestedTuple(*shape_)); CHECK_EQ(src_buf_ptrs.size(), ShapeUtil::TupleElementCount(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); for (int i = 0; i < src_buf_ptrs.size(); ++i) { Piece child_piece; const auto& src_shape = shape_->tuple_shapes(i); CHECK(src_shape.IsArray()); child_piece.set_subshape(&src_shape); child_piece.set_buffer(src_buf_ptrs[i]); root_piece_->emplace_back(std::move(child_piece)); } } } MutableBorrowingLiteral::MutableBorrowingLiteral(ShapeTree<char*> src_buf_ptrs) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(src_buf_ptrs.shape()); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); BuildPieceSubtree(*shape_, root_piece_); root_piece_->ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); } [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); MutableBorrowingLiteral::~MutableBorrowingLiteral() { if (root_piece_ != nullptr) { delete root_piece_; } } LiteralSlice::LiteralSlice(const LiteralBase& literal) : LiteralBase(), root_piece_(&literal.root_piece()) {} LiteralSlice::LiteralSlice(const LiteralBase& literal, const ShapeIndex& view_root) : LiteralBase(), root_piece_(&literal.piece(view_root)) {} BorrowingLiteral::BorrowingLiteral(const char* src_buf_ptr, const Shape& shape) : LiteralBase(), shape_(std::make_unique<Shape>(shape)) { CHECK(shape_->IsArray()); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); root_piece_.set_buffer(const_cast<char*>(src_buf_ptr)); } BorrowingLiteral::BorrowingLiteral(absl::Span<const char* const> src_buf_ptrs, const Shape& shape) : LiteralBase(), shape_(std::make_unique<Shape>(shape)) { CHECK(shape_->IsTuple()); CHECK(!ShapeUtil::IsNestedTuple(*shape_)); CHECK_EQ(src_buf_ptrs.size(), ShapeUtil::TupleElementCount(*shape_)); root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); BuildPieceSubtree(*shape_, &root_piece_); for (int i = 0, end = src_buf_ptrs.size(); i < end; ++i) { const auto& src_shape = shape_->tuple_shapes(i); CHECK(src_shape.IsArray()); root_piece_.child(i).set_buffer(const_cast<char*>(src_buf_ptrs[i])); } } BorrowingLiteral::BorrowingLiteral(ShapeTree<const char*> src_buf_ptrs) : LiteralBase(), shape_(std::make_unique<Shape>(src_buf_ptrs.shape())) { root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); BuildPieceSubtree(*shape_, &root_piece_); root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); } [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); });
#include "xla/literal.h" #include <algorithm> #include <cmath> #include <complex> #include <cstdint> #include <functional> #include <limits> #include <random> #include <string> #include <tuple> #include <utility> #include <vector> #include "absl/base/casts.h" #include "absl/hash/hash.h" #include "absl/random/random.h" #include "absl/status/status.h" #include "absl/strings/match.h" #include "absl/types/span.h" #include "xla/array.h" #include "xla/array2d.h" #include "xla/array3d.h" #include "xla/array4d.h" #include "xla/index_util.h" #include "xla/layout.h" #include "xla/layout_util.h" #include "xla/literal_util.h" #include "xla/primitive_util.h" #include "xla/shape.h" #include "xla/shape_tree.h" #include "xla/shape_util.h" #include "xla/test.h" #include "xla/types.h" #include "xla/util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/errors.h" #include "tsl/platform/logging.h" // IWYU pragma: keep #include "tsl/platform/macros.h" #include "tsl/platform/ml_dtypes.h" #include "tsl/platform/statusor.h" #include "tsl/platform/test_benchmark.h" class LiteralUtilTest : public ::testing::Test { protected: LiteralUtilTest() { Array4D<float> arr4d({ // clang-format off { // i0=0 { // i1=0 {1, 2, 3}, // i2=0 {4, 5, 6}, // i2=1 {7, 8, 9}, // i2=2 }, { // i1=1 {11, 12, 13}, {14, 15, 16}, {17, 18, 19}, }, }, { // i0=1 { // i1=0 {101, 102, 103}, {104, 105, 106}, {107, 108, 109}, }, { // i1=1 {201, 202, 203}, // i2=0 {204, 205, 206}, // i2=1 {207, 208, 209}, // i2=2 }, }, // clang-format on }); layout_r2_dim0major_ = LayoutUtil::MakeLayout({1, 0}); layout_r2_dim0minor_ = LayoutUtil::MakeLayout({0, 1}); layout_r3_dim0major_ = LayoutUtil::MakeLayout({2, 1, 0}); layout_r3_dim0minor_ = LayoutUtil::MakeLayout({0, 1, 2}); layout_r4_dim0major_ = LayoutUtil::MakeLayout({3, 2, 1, 0}); layout_r4_dim0minor_ = LayoutUtil::MakeLayout({0, 1, 2, 3}); literal_r4_2x2x3x3_dim0major_ = LiteralUtil::CreateR4FromArray4DWithLayout<float>(arr4d, layout_r4_dim0major_); literal_r4_2x2x3x3_dim0minor_ = LiteralUtil::CreateR4FromArray4DWithLayout<float>(arr4d, layout_r4_dim0minor_); } Layout layout_r2_dim0major_; Layout layout_r2_dim0minor_; Layout layout_r3_dim0major_; Layout layout_r3_dim0minor_; Layout layout_r4_dim0major_; Layout layout_r4_dim0minor_; Literal literal_r4_2x2x3x3_dim0major_; Literal literal_r4_2x2x3x3_dim0minor_; };
LiteralUtilTest_CopyBetweenSameTuple
xla/literal_test.cc
bool LiteralProtoHasValues(const LiteralProto& proto) { return !proto.s2s().empty() || !proto.s4s().empty() || !proto.s8s().empty() || !proto.s16s().empty() || proto.s32s_size() || proto.s64s_size() || !proto.u2s().empty() || !proto.u4s().empty() || !proto.u8s().empty() || !proto.u16s().empty() || proto.u32s_size() || proto.u64s_size() || !proto.f8e5m2s().empty() || !proto.f8e4m3fns().empty() || !proto.f8e4m3b11fnuzs().empty() || !proto.f8e5m2fnuzs().empty() || !proto.f8e4m3fnuzs().empty() || !proto.f16s().empty() || !proto.bf16s().empty() || proto.f32s_size() || proto.f64s_size() || proto.c64s_size() || proto.c128s_size() || proto.preds_size() || proto.tuple_literals_size(); } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { const Shape& NilShape() { static const Shape* shape = new Shape(TUPLE, {}, {}, {}); return *shape; } const Shape* TryInternShape(const Shape& shape) { if (shape.IsTuple() && shape.tuple_shapes_size() == 0) { return &NilShape(); } if (shape.IsArray() && shape.dimensions_size() == 0 && shape.is_static() && shape.layout().tiles_size() == 0 && shape.layout().memory_space() == 0) { return &ScalarShape(shape.element_type()); } return nullptr; } StrideConfig::StrideConfig(const Shape& source_shape, const Shape& dest_shape, absl::Span<const int64_t> dimensions) : dimensions(dimensions), base(dimensions.size(), 0), step(dimensions.size(), 1) { if (!dimensions.empty()) { // Selects the shape with the largest minor dimension as the one upon // which to run the tight stride loop. if (dimensions[LayoutUtil::Minor(source_shape.layout(), 0)] >= dimensions[LayoutUtil::Minor(dest_shape.layout(), 0)]) { minor_dimension = LayoutUtil::Minor(source_shape.layout(), 0); dest_stride = IndexUtil::GetDimensionStride(dest_shape, minor_dimension); } else { minor_dimension = LayoutUtil::Minor(dest_shape.layout(), 0); source_stride = IndexUtil::GetDimensionStride(source_shape, minor_dimension); } minor_loop_size = dimensions[minor_dimension]; step[minor_dimension] = minor_loop_size; } } LiteralBase::~LiteralBase() = default; const Shape& LiteralBase::shape() const { return root_piece().subshape(); } const char* LiteralBase::Piece::buffer() const { // std::visit is avoided here due to its code size issues. if (auto* r = std::get_if<DenseRep>(&rep_)) { return r->data; } if (auto* r = std::get_if<DenseInlinedRep>(&rep_)) { return r->data; } DCHECK(std::holds_alternative<TupleRep>(rep_) || std::holds_alternative<Uninitialized>(rep_)); return nullptr; } const LiteralBase::Piece& LiteralBase::piece( const ShapeIndex& shape_index) const { const Piece* piece = &root_piece(); for (const auto i : shape_index) { DCHECK_GE(i, 0); DCHECK_LT(i, piece->children_size()); piece = &piece->child(i); } return *piece; } std::ostream& operator<<(std::ostream& out, const Literal& literal) { out << literal.ToString(); return out; } Shape* MutableLiteralBase::mutable_shape_do_not_use() { const Shape* const_shape = shape_.get(); if (!shape_.OwnsPtr()) { shape_ = MaybeOwningShapePtr(std::make_unique<Shape>(*shape_)); } Shape* shape = shape_.get_mutable(); if (shape != const_shape) { std::function<void(const Shape&, Piece*)> set_piece_shapes = [&set_piece_shapes](const Shape& shape, Piece* piece) { piece->set_subshape(&shape); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); set_piece_shapes(subshape, &piece->child(i)); } } }; set_piece_shapes(*shape, &mutable_root_piece()); } return shape; } [&set_piece_shapes](const Shape& shape, Piece* piece) { piece->set_subshape(&shape); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); set_piece_shapes(subshape, &piece->child(i)); } } }; Literal::Literal() : Literal(NilShape()) {} Literal::Literal(const Shape& shape) : Literal(shape, /*allocate_arrays=*/true) {} void Literal::SetShape(const Shape& shape) { Shape shape_storage; const Shape* shape_ptr = &shape; if (LayoutUtil::HasCustomElementSizeInBits(shape)) { shape_storage = shape; shape_storage.mutable_layout()->set_element_size_in_bits(0); shape_ptr = &shape_storage; } if (const Shape* intered_shape_ptr = TryInternShape(*shape_ptr)) { shape_ = intered_shape_ptr; } else { shape_ = std::make_unique<Shape>(*shape_ptr); } } void Literal::SetPiece(const Shape& shape, Piece* piece, bool allocate_arrays, ArrayValueState leaf_array_value_state) { if (shape.IsTuple()) { for (const Shape& subshape : shape.tuple_shapes()) { Piece child_piece; child_piece.set_subshape(&subshape); SetPiece(subshape, &child_piece, allocate_arrays, leaf_array_value_state); piece->emplace_back(std::move(child_piece)); } } else if (shape.IsArray()) { DCHECK(LayoutUtil::IsDenseArray(shape)) << "literal array storage is currently only supported for dense " "arrays: " << shape; piece->set_array_value_state(leaf_array_value_state); if (leaf_array_value_state == LiteralBase::ArrayValueState::kKnown && allocate_arrays) { piece->AllocateBuffers(); } } } Literal::Literal(const Shape& shape, bool allocate_arrays, ArrayValueState leaf_array_value_state) : MutableLiteralBase() { SetShape(shape); CHECK(leaf_array_value_state != ArrayValueState::kKnown || LayoutUtil::HasLayout(*shape_)); root_piece_.set_subshape(shape_.get()); CHECK(&root_piece_.subshape() == shape_.get()); SetPiece(*shape_, &root_piece_, allocate_arrays, leaf_array_value_state); } Literal::~Literal() { DeallocateBuffers(); } void Literal::DeallocateBuffers() { root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { piece->DeallocateBuffers(); }); } Literal::Literal(Literal&& other) : MutableLiteralBase() { *this = std::move(other); } Literal& Literal::operator=(Literal&& other) { DCHECK(&other.root_piece_.subshape() == other.shape_.get()); using std::swap; swap(shape_, other.shape_); swap(root_piece_, other.root_piece_); DCHECK(&root_piece_.subshape() == shape_.get()); return *this; } Literal LiteralBase::CreateFromShape(const Shape& shape) { Literal literal(shape); literal.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (piece->subshape().IsArray()) { memset(piece->untyped_data(), 0, piece->size_bytes_dense()); } }); return literal; } [&](const ShapeIndex& index, Piece* piece) { if (piece->subshape().IsArray()) { memset(piece->untyped_data(), 0, piece->size_bytes_dense()); } }); Literal LiteralBase::CreateFromShapeWithUnknownLeafArrays(const Shape& shape) { Literal literal(shape, /*allocate_arrays=*/false, ArrayValueState::kUnknown); return literal; } Literal LiteralBase::CreateFromShapeWithUndeterminedLeafArrays( const Shape& shape) { Literal literal(shape, /*allocate_arrays=*/false, ArrayValueState::kUndetermined); return literal; } int32_t LiteralBase::GetDynamicSize(int64_t dim_index) const { return GetDynamicSize(dim_index, {}); } int32_t LiteralBase::GetDynamicSize(int64_t dim_index, const ShapeIndex& shape_index) const { return piece(shape_index).GetDynamicSize(dim_index); } std::optional<int64_t> LiteralBase::GetFirstInteger() const { if (!primitive_util::IsIntegralType(shape().element_type())) { return std::nullopt; } return primitive_util::IntegralTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, void LiteralBase::BuildPieceSubtree(const Shape& shape, Piece* piece) { CHECK(shape.IsTuple()); for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); Piece child_piece; child_piece.set_subshape(&subshape); if (subshape.IsTuple()) { BuildPieceSubtree(subshape, &child_piece); } piece->emplace_back(std::move(child_piece)); } } absl::Status LiteralBase::SerializeToString(std::string* output) const { ShapeProto shape_proto = shape().ToProto(); TF_ASSIGN_OR_RETURN(int64_t size, ShapeUtil::SerializedSizeWithProto(shape(), shape_proto)); output->resize(size); return SerializeWithShapeProto(shape_proto, output->data()); } absl::StatusOr<std::string> LiteralBase::SerializeAsString() const { std::string result; TF_RETURN_IF_ERROR(SerializeToString(&result)); return std::move(result); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { void MutableLiteralBase::CopyElementFrom(const LiteralSlice& src_literal, absl::Span<const int64_t> src_index, absl::Span<const int64_t> dest_index) { DCHECK(LayoutUtil::IsDenseArray(shape())); DCHECK_EQ(shape().element_type(), src_literal.shape().element_type()); const int64_t src_linear_index = IndexUtil::MultidimensionalIndexToLinearIndex(src_literal.shape(), src_index); const int64_t dest_linear_index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), dest_index); const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); char* dest_address = static_cast<char*>(untyped_data()) + dest_linear_index * primitive_size; const char* source_address = static_cast<const char*>(src_literal.untyped_data()) + src_linear_index * primitive_size; if (dest_address != source_address) { memcpy(dest_address, source_address, primitive_size); } } /* static */ absl::StatusOr<Literal> MutableLiteralBase::CreateFromProto( const LiteralProto& proto, bool prohibit_empty_literal) { if (!proto.has_shape()) { return InvalidArgument("LiteralProto has no shape"); } Shape shape(proto.shape()); if (ShapeUtil::HasPrimitiveType(shape, OPAQUE_TYPE)) { return InvalidArgument( "Literal shape cannot include OPAQUE_TYPE sub-shape"); } if (!LayoutUtil::HasLayout(shape)) { return InvalidArgument("LiteralProto has no layout"); } if (LayoutUtil::IsSparseArray(shape)) { return Unimplemented("Sparse literals are not supported"); } TF_RETURN_IF_ERROR(ShapeUtil::ValidateShapeWithOptionalLayout(shape)); Literal literal(shape); TF_RETURN_IF_ERROR(literal.root_piece_.ForEachMutableSubpieceWithStatus( [&](const ShapeIndex& index, Piece* piece) -> absl::Status { const LiteralProto* proto_element = &proto; for (int64_t i : index) { CHECK(i < proto_element->tuple_literals_size()); proto_element = &proto_element->tuple_literals(i); } if (piece->subshape().IsTuple()) { if (proto_element->tuple_literals_size() != ShapeUtil::TupleElementCount(piece->subshape())) { return InvalidArgument( "Expected %d tuple elements in LiteralProto, has %d", ShapeUtil::TupleElementCount(piece->subshape()), proto_element->tuple_literals_size()); } return absl::OkStatus(); } if (piece->subshape().element_type() == TOKEN) { return absl::OkStatus(); } CHECK(piece->subshape().IsArray()); // When prohibit_empty_literal is false (allowing literal with no // values), only copy from proto if the literal proto has values. This // mode is used for a learned cost model. if (prohibit_empty_literal || LiteralProtoHasValues(*proto_element)) { TF_RETURN_IF_ERROR(piece->CopyFromProto(*proto_element)); } return absl::OkStatus(); })); return std::move(literal); } TF_RETURN_IF_ERROR(literal.root_piece_.ForEachMutableSubpieceWithStatus( Literal Literal::SubLiteral(ShapeIndexView shape_index) { if (!shape_index.empty()) { auto decomposed = this->DecomposeTuple(); return decomposed.at(shape_index.front()) .SubLiteral(shape_index.subspan(1)); } else { return std::move(*this); } } std::vector<Literal> Literal::DecomposeTuple() { CHECK(shape().IsTuple()); std::vector<Literal> elements; const auto tuple_element_count = ShapeUtil::TupleElementCount(shape()); elements.reserve(tuple_element_count); for (int i = 0; i < tuple_element_count; ++i) { elements.push_back(Literal(ShapeUtil::GetSubshape(shape(), {i}), /*allocate_arrays=*/false)); Literal& element = elements.back(); element.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* dest_piece) { if (dest_piece->subshape().IsTuple()) { return; } ShapeIndex src_index = {i}; for (int64_t j : index) { src_index.push_back(j); } Piece& src_piece = piece(src_index); // Move the respective buffer over to the element Literal. dest_piece->MoveDataFrom(src_piece); }); } // Set this literal to be nil-shaped. *this = Literal(); return elements; } [&](const ShapeIndex& index, Piece* dest_piece) { if (dest_piece->subshape().IsTuple()) { return; } ShapeIndex src_index = {i}; for (int64_t j : index) { src_index.push_back(j); } Piece& src_piece = piece(src_index); // Move the respective buffer over to the element Literal. dest_piece->MoveDataFrom(src_piece); }); void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } int32_t LiteralBase::Piece::GetDynamicSize(int64_t dim_index) const { CHECK(LayoutUtil::IsDenseArray(subshape())); if (!subshape_->is_dynamic_dimension(dim_index)) { // This is a static dimension, return size. return subshape_->dimensions(dim_index); } return dynamic_size_buffer()[dim_index]; } void LiteralBase::Piece::SetDynamicSize(int64_t dim_index, int32_t size) { CHECK(LayoutUtil::IsDenseArray(subshape())); CHECK(subshape_->is_dynamic_dimension(dim_index)); dynamic_size_buffer()[dim_index] = size; } void LiteralBase::Piece::AllocateBuffers() { const int64_t bytes = total_bytes_dense(); if (bytes > kMaxInlinedBytes) { CHECK_EQ(buffer(), nullptr); rep_.emplace<DenseRep>(); set_buffer( static_cast<char*>(tsl::port::AlignedMalloc(bytes, kMinimumAlignment))); } else { rep_.emplace<DenseInlinedRep>(); } } void LiteralBase::Piece::DeallocateBuffers() { if (auto* array_rep = GetDenseRep()) { tsl::port::AlignedFree(array_rep->data); rep_.emplace<Uninitialized>(); } } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } absl::Status LiteralBase::Piece::CopyFrom(const LiteralBase::Piece& src, bool only_dynamic_bound) { CHECK(subshape_ != nullptr); CHECK(src.subshape_ != nullptr); CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK(LayoutUtil::IsDenseArray(src.subshape())) << __func__ << " is only supported for dense arrays: " << src.subshape(); if (!only_dynamic_bound) { CHECK(ShapeUtil::Compatible(subshape(), src.subshape())); } if (src.array_value_state_ == ArrayValueState::kUnknown || src.array_value_state_ == ArrayValueState::kUndetermined) { if (array_value_state_ == ArrayValueState::kKnown) { DeallocateBuffers(); } array_value_state_ = src.array_value_state_; return absl::OkStatus(); } else { CHECK(src.array_value_state_ == ArrayValueState::kKnown); if (array_value_state_ == ArrayValueState::kUndetermined || array_value_state_ == ArrayValueState::kUnknown) { AllocateBuffers(); } array_value_state_ = src.array_value_state_; } if (ShapeUtil::Equal(subshape(), src.subshape())) { // If the layouts are equal it's faster just to memcpy. memcpy(buffer(), src.buffer(), src.size_bytes_dense()); } else { std::vector<int64_t> origin(subshape().rank(), 0); primitive_util::ArrayTypeSwitch<void>( [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, subshape().element_type()); } DCHECK_EQ(dynamic_size_buffer_bytes(), src.dynamic_size_buffer_bytes()); if (subshape().is_dynamic() && src.subshape().is_dynamic()) { memcpy(dynamic_size_buffer(), src.dynamic_size_buffer(), src.dynamic_size_buffer_bytes()); } return absl::OkStatus(); } [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, void MutableLiteralBase::SetDynamicSize(int64_t dim_index, int32_t size) { return SetDynamicSize(dim_index, {}, size); } void MutableLiteralBase::SetDynamicSize(int64_t dim_index, const ShapeIndex& shape_index, int32_t size) { Shape* subshape = ShapeUtil::GetMutableSubshape(mutable_shape_do_not_use(), shape_index); CHECK(LayoutUtil::IsDenseArray(*subshape)) << __func__ << " is only supported for dense arrays: " << *subshape; CHECK_GE(subshape->dimensions(dim_index), size); subshape->set_dynamic_dimension(dim_index, true); CHECK_EQ(&piece(shape_index).subshape(), subshape); piece(shape_index).SetDynamicSize(dim_index, size); } absl::Status MutableLiteralBase::CopyFrom(const LiteralSlice& src_literal, const ShapeIndex& dest_shape_index, const ShapeIndex& src_shape_index, bool only_dynamic_bound) { const Shape& dest_subshape = ShapeUtil::GetSubshape(shape(), dest_shape_index); const Shape& src_subshape = ShapeUtil::GetSubshape(src_literal.shape(), src_shape_index); if (only_dynamic_bound) { auto& bound_shape = dest_subshape.is_static() ? src_subshape : dest_subshape; auto& compact_shape = dest_subshape.is_static() ? dest_subshape : src_subshape; CHECK(ShapeUtil::DynamicShapeIsCompatible(compact_shape, bound_shape)) << compact_shape.ToString() << " vs " << bound_shape.ToString(); } else { if (!ShapeUtil::Compatible(dest_subshape, src_subshape)) { return InvalidArgument( "Destination subshape incompatible with source subshape: %s vs %s", ShapeUtil::HumanString(dest_subshape), ShapeUtil::HumanString(src_subshape)); } } return mutable_root_piece().ForEachMutableSubpieceWithStatus( [&](const ShapeIndex& index, Piece* piece) { if (!piece->subshape().IsArray()) { return absl::OkStatus(); } // Determine if this index is in the part of this literal that we want // to copy over from src_literal. bool in_subtree_to_copy = true; for (int i = 0; i < dest_shape_index.size(); ++i) { if (index[i] != dest_shape_index[i]) { in_subtree_to_copy = false; break; } } if (!in_subtree_to_copy) { return absl::OkStatus(); } // Construct the index of the corresponding piece in the source literal. ShapeIndex src_piece_index = src_shape_index; for (int64_t i = dest_shape_index.size(), end = index.size(); i < end; ++i) { src_piece_index.push_back(index[i]); } TF_RETURN_IF_ERROR( piece->CopyFrom(src_literal.piece(src_piece_index), /*only_dynamic_bound=*/only_dynamic_bound)); return absl::OkStatus(); }); } [&](const ShapeIndex& index, Piece* piece) { if (!piece->subshape().IsArray()) { return absl::OkStatus(); } // Determine if this index is in the part of this literal that we want // to copy over from src_literal. bool in_subtree_to_copy = true; for (int i = 0; i < dest_shape_index.size(); ++i) { if (index[i] != dest_shape_index[i]) { in_subtree_to_copy = false; break; } } if (!in_subtree_to_copy) { return absl::OkStatus(); } // Construct the index of the corresponding piece in the source literal. ShapeIndex src_piece_index = src_shape_index; for (int64_t i = dest_shape_index.size(), end = index.size(); i < end; ++i) { src_piece_index.push_back(index[i]); } TF_RETURN_IF_ERROR( piece->CopyFrom(src_literal.piece(src_piece_index), /*only_dynamic_bound=*/only_dynamic_bound)); return absl::OkStatus(); }); absl::Status Literal::MoveFrom(Literal&& src_literal, const ShapeIndex& dest_shape_index) { const Shape& dest_subshape = ShapeUtil::GetSubshape(shape(), dest_shape_index); if (!ShapeUtil::Equal(dest_subshape, src_literal.shape())) { return InvalidArgument( "Destination subshape not equal to source shape: %s vs %s", ShapeUtil::HumanString(dest_subshape), ShapeUtil::HumanString(src_literal.shape())); } src_literal.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& src_index, Piece* src_piece) { if (!src_piece->subshape().IsArray()) { return; } ShapeIndex dest_index = dest_shape_index; for (int64_t i : src_index) { dest_index.push_back(i); } Piece& dest_piece = piece(dest_index); dest_piece.DeallocateBuffers(); dest_piece.MoveDataFrom(*src_piece); }); src_literal.shape_ = MaybeOwningShapePtr(&NilShape()); src_literal.root_piece_ = Piece(); src_literal.root_piece_.set_subshape(src_literal.shape_.get()); return absl::OkStatus(); } [&](const ShapeIndex& src_index, Piece* src_piece) { if (!src_piece->subshape().IsArray()) { return; } ShapeIndex dest_index = dest_shape_index; for (int64_t i : src_index) { dest_index.push_back(i); } Piece& dest_piece = piece(dest_index); dest_piece.DeallocateBuffers(); dest_piece.MoveDataFrom(*src_piece); }); absl::Status MutableLiteralBase::CopySliceFrom( const LiteralSlice& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << shape(); TF_RET_CHECK(LayoutUtil::IsDenseArray(src_literal.shape())) << src_literal.shape(); TF_RET_CHECK(ShapeUtil::SameElementType(src_literal.shape(), shape())); TF_RET_CHECK(src_literal.shape().rank() == src_base.size()); TF_RET_CHECK(shape().rank() == dest_base.size()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, void MutableLiteralBase::PopulateR1(const tsl::core::Bitmap& values) { CHECK(shape().IsArray()); CHECK_EQ(shape().rank(), 1); CHECK_EQ(element_count(), values.bits()); CHECK_EQ(shape().element_type(), PRED); for (int64_t i = 0; i < static_cast<int64_t>(values.bits()); ++i) { Set({i}, values.get(i)); } } void MutableLiteralBase::PopulateInplaceInternal( absl::FunctionRef<void(void*, absl::Span<const int64_t>, int)> populator, bool parallel) { const Shape& this_shape = shape(); const int64_t rank = this_shape.rank(); DCHECK(LayoutUtil::IsDenseArray(this_shape)); char* const dest_base = static_cast<char*>(untyped_data()); if (rank > 0) { StrideConfig stride_config(this_shape, this_shape, this_shape.dimensions()); const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); const int64_t num_elements = ShapeUtil::ElementsIn(shape()); // If we are rank-1 and we are `parallel`, it is better to use a smaller // `step` than what `StrideConfig` does: stick the entire dimension in the // inner-most loop. if (parallel && this_shape.rank() == 1) { const int64_t thread_count = ShapeUtil::GetForEachIndexParallelThreadCount(); // Let's just divide up the array into small amounts per thread. stride_config.dest_stride = stride_config.minor_loop_size = num_elements > 32 ? std::max<int64_t>(num_elements / thread_count, 1) : num_elements; stride_config.step = {stride_config.minor_loop_size}; } auto init_function = [&](absl::Span<const int64_t> indexes, int thread_id) -> absl::StatusOr<bool> { const int64_t index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), indexes); DimensionVector minor_scan_indexes(rank, 0); std::copy(indexes.begin(), indexes.end(), minor_scan_indexes.begin()); char* dest_ptr = dest_base + index * primitive_size; char* const dest_end = dest_base + // This handles the case where minor_loop_size does not evenly divide // the most minor dimension. std::min(index + stride_config.minor_loop_size, num_elements) * primitive_size; while (dest_ptr < dest_end) { populator(dest_ptr, minor_scan_indexes, thread_id); ++minor_scan_indexes[stride_config.minor_dimension]; dest_ptr += primitive_size; } return true; }; if (parallel) { ShapeUtil::ForEachIndexParallel(this_shape, stride_config.base, stride_config.dimensions, stride_config.step, init_function); } else { ShapeUtil::ForEachIndex( this_shape, stride_config.base, stride_config.dimensions, stride_config.step, [&init_function]( absl::Span<const int64_t> indexes) -> absl::StatusOr<bool> { auto result_ignored = init_function(indexes, /*thread_id=*/-1); return true; }); } } else { // For scalars. populator(dest_base, {}, /*thread_id=*/-1); } } auto init_function = [&](absl::Span<const int64_t> indexes, int thread_id) -> absl::StatusOr<bool> { const int64_t index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), indexes); DimensionVector minor_scan_indexes(rank, 0); std::copy(indexes.begin(), indexes.end(), minor_scan_indexes.begin()); char* dest_ptr = dest_base + index * primitive_size; char* const dest_end = dest_base + // This handles the case where minor_loop_size does not evenly divide // the most minor dimension. std::min(index + stride_config.minor_loop_size, num_elements) * primitive_size; while (dest_ptr < dest_end) { populator(dest_ptr, minor_scan_indexes, thread_id); ++minor_scan_indexes[stride_config.minor_dimension]; dest_ptr += primitive_size; } return true; }; [&init_function]( absl::Span<const int64_t> indexes) -> absl::StatusOr<bool> { auto result_ignored = init_function(indexes, /*thread_id=*/-1); return true; }); absl::Status MutableLiteralBase::PopulateInplace( absl::FunctionRef<void(void*, absl::Span<const int64_t>)> populator) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); PopulateInplaceInternal( [&](void* dest, absl::Span<const int64_t> indexes, int /*thread_id*/) { return populator(dest, indexes); }, /*parallel=*/false); return absl::OkStatus(); } absl::Status MutableLiteralBase::PopulateInplaceParallel( absl::FunctionRef<void(void*, absl::Span<const int64_t>, int)> populator) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); PopulateInplaceInternal(populator, /*parallel=*/element_count() > 32); return absl::OkStatus(); } Literal LiteralBase::Relayout(const Layout& new_layout, const ShapeIndex& shape_index) const { // Create new shape with 'new_layout' set at the given shape index. Shape new_shape = shape(); Shape* subshape = ShapeUtil::GetMutableSubshape(&new_shape, shape_index); TF_CHECK_OK(LayoutUtil::ValidateLayoutForShape(new_layout, *subshape)); *subshape->mutable_layout() = new_layout; // LINT.IfChange // s4 literals are stored in uint8_t/int8_t, therefore element_size_in_bits // must be removed. if (subshape->layout().element_size_in_bits() == 4) { subshape->mutable_layout()->set_element_size_in_bits(0); } // LINT.ThenChange(//tensorflow/compiler/xla/types.h) Literal result(new_shape); TF_CHECK_OK(result.CopyFrom(*this)); return result; } Literal LiteralBase::Relayout(const Shape& shape_with_layout) const { CHECK(ShapeUtil::Compatible(shape_with_layout, shape())) << "Given shape_with_layout " << ShapeUtil::HumanString(shape_with_layout) << " not compatible with literal shape " << ShapeUtil::HumanString(shape()); Literal result = CreateFromShape(shape_with_layout); ShapeUtil::ForEachSubshape( result.shape(), [this, &result](const Shape& subshape, const ShapeIndex& index) { if (subshape.IsArray()) { TF_CHECK_OK(result.CopyFrom(*this, /*dest_shape_index=*/index, /*src_shape_index=*/index)); } }); return result; } [this, &result](const Shape& subshape, const ShapeIndex& index) { if (subshape.IsArray()) { TF_CHECK_OK(result.CopyFrom(*this, /*dest_shape_index=*/index, /*src_shape_index=*/index)); } }); Literal LiteralBase::ToBoundedDynamic(const Shape& bounded_shape) const { CHECK(bounded_shape.is_dynamic()); Literal result(bounded_shape); ShapeUtil::ForEachSubshape( shape(), [&](const Shape& subshape, const ShapeIndex& index) { if (!subshape.IsArray()) { return; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (bounded_shape.is_dynamic_dimension(i)) { result.SetDynamicSize(i, subshape.dimensions(i)); } } }); TF_CHECK_OK(result.CopyFrom(*this, {}, {}, /*only_dynamic_bound=*/true)); return result; } shape(), [&](const Shape& subshape, const ShapeIndex& index) { if (!subshape.IsArray()) { return; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (bounded_shape.is_dynamic_dimension(i)) { result.SetDynamicSize(i, subshape.dimensions(i)); } } }); Literal LiteralBase::ToStatic() const { // Create new shape with 'new_layout' set at the given shape index. Shape new_shape = shape(); ShapeUtil::ForEachMutableSubshape( &new_shape, [this](Shape* subshape, const ShapeIndex& index) { if (!subshape->IsArray()) { return; } for (int64_t i = 0; i < subshape->rank(); ++i) { // GetDynamicSize has a 32-bit return type and may truncate static // dimensions, so make sure to skip. if (!subshape->is_dynamic_dimension(i)) continue; subshape->set_dynamic_dimension(i, false); subshape->set_dimensions(i, GetDynamicSize(i, index)); } }); Literal result(new_shape); TF_CHECK_OK(result.CopyFrom(*this, {}, {}, /*only_dynamic_bound=*/true)); return result; } &new_shape, [this](Shape* subshape, const ShapeIndex& index) { if (!subshape->IsArray()) { return; } for (int64_t i = 0; i < subshape->rank(); ++i) { // GetDynamicSize has a 32-bit return type and may truncate static // dimensions, so make sure to skip. if (!subshape->is_dynamic_dimension(i)) continue; subshape->set_dynamic_dimension(i, false); subshape->set_dimensions(i, GetDynamicSize(i, index)); } }); absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { absl::StatusOr<Literal> LiteralBase::Broadcast( const Shape& result_shape, absl::Span<const int64_t> dimensions) const { const LiteralBase& src = *this; const Shape& src_shape = shape(); if (!src_shape.IsArray()) { return InvalidArgument("Broadcast only supports arrays."); } const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(src_shape.element_type()); switch (primitive_size) { case 0: return BroadcastHelper<0>(src, src_shape, result_shape, dimensions); case 1: return BroadcastHelper<1>(src, src_shape, result_shape, dimensions); case 2: return BroadcastHelper<2>(src, src_shape, result_shape, dimensions); case 4: return BroadcastHelper<4>(src, src_shape, result_shape, dimensions); case 8: return BroadcastHelper<8>(src, src_shape, result_shape, dimensions); case 16: return BroadcastHelper<16>(src, src_shape, result_shape, dimensions); default: LOG(FATAL) << "Unhandled primitive size " << primitive_size; return InvalidArgument("Unhandled primitive size"); break; } } absl::StatusOr<Literal> LiteralBase::Reshape( absl::Span<const int64_t> dimensions) const { if (!LayoutUtil::IsDenseArray(shape())) { return InvalidArgument("Reshape is only supported for dense arrays."); } if (shape().is_dynamic()) { // TODO(b/243182930): We should consider supporting dynamic reshape. return Unimplemented("Dynamic reshape is not implemented."); } Literal output; if (!LayoutUtil::IsMonotonicWithDim0Major(shape().layout())) { output = Relayout(LayoutUtil::GetDefaultLayoutForRank(shape().rank())); } else { output = Clone(); } // Because the layout is monotonic, we can simply reuse the same sequence of // values without changing their order. *output.mutable_shape_do_not_use() = ShapeUtil::MakeShape(shape().element_type(), dimensions); int64_t elements_before = ShapeUtil::ElementsIn(shape()); int64_t elements_after = ShapeUtil::ElementsIn(output.shape()); if (elements_before != elements_after) { return InvalidArgument( "Shapes before and after Literal::Reshape have different numbers " "of elements: %s vs %s.", ShapeUtil::HumanString(shape()), ShapeUtil::HumanString(output.shape())); } return std::move(output); } Literal LiteralBase::Transpose(absl::Span<const int64_t> permutation) const { CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); CHECK(shape().rank() == permutation.size() && IsPermutation(permutation)) << "Given permutation is not a permutation of dimension numbers"; // To transpose the array, we just permute the dimensions and layout, and // do a straight memory copy of the raw data set. // This is considerably faster than iterating over every array element using // the EachCell<>() and Set<>() APIs. Shape permuted_shape = ShapeUtil::PermuteDimensions(permutation, shape()); // Replace the layout with one affine to this shape, such that a // transpose operation can be performed by leaving the flat values // representation intact. // For example, consider the shape F32[11,8]{1,0} under a {1,0} permutation. // The shape with affine layout resulting from that operation will be // F32[8,11]{0,1}, since it leaves the original most minor (the 8 sized), the // most minor. // // Essentially, given MinMaj(Di) the position of the Di dimension within the // minor to major vector, and given T(Di) the index that the original Di // dimension has within the transposed array, a layout is affine if // MinMaj(Di) == TMinMaj(T(Di)), with TMinMaj() being the minor to major // vector of the affine layout. std::vector<int64_t> inverse_permutation = InversePermutation(permutation); CHECK(LayoutUtil::IsDenseArray(permuted_shape)); Layout* layout = permuted_shape.mutable_layout(); layout->clear_minor_to_major(); for (auto index : LayoutUtil::MinorToMajor(shape())) { layout->add_minor_to_major(inverse_permutation[index]); } Literal new_literal(permuted_shape); if (shape().is_dynamic()) { for (int64_t i = 0; i < shape().rank(); i++) { if (shape().is_dynamic_dimension(i)) { // Set the dynamic size of any dynamic dimension in the transposed // literal. new_literal.SetDynamicSize(inverse_permutation[i], GetDynamicSize(i)); } } } DCHECK_EQ(ShapeUtil::ByteSizeOf(new_literal.shape()), ShapeUtil::ByteSizeOf(shape())); std::memcpy(new_literal.untyped_data(), untyped_data(), size_bytes()); return new_literal; } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( Literal LiteralBase::Slice(absl::Span<const int64_t> start_indices, absl::Span<const int64_t> limit_indices) const { CHECK(shape().IsArray()) << "tuple is not supported for slice"; DimensionVector result_dimensions; for (int64_t dnum = 0; dnum < shape().rank(); ++dnum) { CHECK_GE(start_indices[dnum], 0); CHECK_LE(limit_indices[dnum], shape().dimensions(dnum)) << "dnum = " << dnum; int64_t dimension = limit_indices[dnum] - start_indices[dnum]; CHECK_GE(dimension, 0) << "dnum = " << dnum; result_dimensions.push_back(dimension); } auto result_shape = ShapeUtil::MakeShapeWithDenseLayout( shape().element_type(), result_dimensions, LayoutUtil::MinorToMajor(shape())); ShapeUtil::CopyDynamicDimensions(&result_shape, shape()); Literal result_literal(result_shape); primitive_util::ArrayTypeSwitch<void>( [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; return SliceInternal<NativeT>(*this, start_indices, result_literal); }, result_shape.element_type()); return result_literal; } Literal LiteralBase::Clone() const { Literal result(shape()); TF_CHECK_OK(result.CopyFrom(*this)); return result; } std::unique_ptr<Literal> LiteralBase::CloneToUnique() const { auto result = std::make_unique<Literal>(shape()); TF_CHECK_OK(result->CopyFrom(*this)); return result; } bool LiteralBase::IsDetermined(const ShapeIndex& shape_index) const { return piece(shape_index).IsDetermined(); } bool LiteralBase::IsKnown(const ShapeIndex& shape_index) const { return piece(shape_index).IsKnown(); } std::string LiteralBase::GetAsString(absl::Span<const int64_t> multi_index, const ShapeIndex& shape_index) const { const Shape& subshape = ShapeUtil::GetSubshape(shape(), shape_index); CHECK(LayoutUtil::IsDenseArray(subshape)); return primitive_util::ArrayTypeSwitch<std::string>( [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, subshape.element_type()); } [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, std::optional<int64_t> LiteralBase::GetIntegralAsS64( absl::Span<const int64_t> multi_index) const { CHECK(LayoutUtil::IsDenseArray(shape())); return primitive_util::PrimitiveTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, std::optional<double> LiteralBase::GetAsDouble( absl::Span<const int64_t> multi_index) const { const Shape& s = shape(); CHECK(LayoutUtil::IsDenseArray(s)); return primitive_util::PrimitiveTypeSwitch<std::optional<double>>( [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, s.element_type()); } [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, std::optional<double> LiteralBase::GetSumAsDouble( absl::Span<const int64_t> linear_indices) const { const Shape& s = shape(); CHECK(LayoutUtil::IsDenseArray(s)); if (!primitive_util::IsFloatingPointType(s.element_type())) { return std::nullopt; } return primitive_util::FloatingPointTypeSwitch<double>( [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, s.element_type()); } [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, std::optional<complex128> LiteralBase::GetAsComplex128( absl::Span<const int64_t> multi_index) const { return primitive_util::PrimitiveTypeSwitch<std::optional<complex128>>( [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, absl::Status MutableLiteralBase::SetIntegralAsS64( absl::Span<const int64_t> multi_index, int64_t value) { CHECK(LayoutUtil::IsDenseArray(shape())); return primitive_util::PrimitiveTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, absl::Status MutableLiteralBase::SetFromDouble( absl::Span<const int64_t> multi_index, double value) { CHECK(LayoutUtil::IsDenseArray(shape())); if (!primitive_util::IsFloatingPointType(shape().element_type())) { return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); } primitive_util::FloatingPointTypeSwitch<void>( [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, shape().element_type()); return absl::OkStatus(); } [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, void PrintShape(bool print_layout, const Shape& shape, Printer* printer) { if (print_layout) { ShapeUtil::PrintHumanStringWithLayout(printer, shape); } else { ShapeUtil::PrintHumanString(printer, shape); } } void TuplePrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); printer->Append(oneline ? "( " : "(\n"); for (int i = 0; i < ShapeUtil::TupleElementCount(subshape); ++i) { ShapeIndex element_index = shape_index; element_index.push_back(i); if (i > 0) printer->Append(oneline ? ", " : ",\n"); PrintHelper(literal, element_index, print_shape, print_layout, oneline, printer); } printer->Append(oneline ? " )" : "\n)"); } void DenseArrayPrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); int64_t rank = subshape.rank(); const absl::string_view linebreak = oneline ? " " : "\n"; std::function<void(absl::Span<const int64_t> dimensions, std::vector<int64_t>*)> print_recursive = [&](absl::Span<const int64_t> dimensions, std::vector<int64_t>* accum_indices) { // dimensions.size() decreases by 1 at each recursive call, // and accum_indices->size() increases by 1. // Their sum is equal to the rank of the tensor. CHECK_EQ(rank, dimensions.size() + accum_indices->size()); auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; if (dimensions.empty()) { // Display predicates as 0s and 1s so that the string is more dense. std::string elem; if (subshape.element_type() == PRED && rank > 0) { elem = literal.Get<bool>(*accum_indices, shape_index) ? "1" : "0"; } else { elem = literal.GetAsString(*accum_indices, shape_index); } printer->Append(elem); } else { printer->Append(brace_to_string("{")); for (int i = 0; i < dimensions[0]; ++i) { accum_indices->push_back(i); print_recursive(dimensions.subspan(1), accum_indices); accum_indices->pop_back(); if (i < dimensions[0] - 1) { printer->Append(","); printer->Append(dimensions.size() > 1 ? linebreak : " "); } } printer->Append(brace_to_string("}")); } }; if (print_shape) { PrintShape(print_layout, subshape, printer); if (subshape.is_dynamic()) { printer->Append("("); for (int64_t i = 0; i < subshape.dimensions_size(); ++i) { printer->Append(literal.GetDynamicSize(i, shape_index)); if (i < subshape.dimensions_size() - 1) { printer->Append(","); } } printer->Append(")"); } printer->Append(" "); } std::vector<int64_t> indices = {}; std::vector<int64_t> dimensions; dimensions.reserve(subshape.rank()); for (int64_t i = 0; i < subshape.rank(); ++i) { dimensions.push_back(literal.GetDynamicSize(i, shape_index)); } print_recursive(dimensions, &indices); } print_recursive = [&](absl::Span<const int64_t> dimensions, std::vector<int64_t>* accum_indices) { // dimensions.size() decreases by 1 at each recursive call, // and accum_indices->size() increases by 1. // Their sum is equal to the rank of the tensor. CHECK_EQ(rank, dimensions.size() + accum_indices->size()); auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; if (dimensions.empty()) { // Display predicates as 0s and 1s so that the string is more dense. std::string elem; if (subshape.element_type() == PRED && rank > 0) { elem = literal.Get<bool>(*accum_indices, shape_index) ? "1" : "0"; } else { elem = literal.GetAsString(*accum_indices, shape_index); } printer->Append(elem); } else { printer->Append(brace_to_string("{")); for (int i = 0; i < dimensions[0]; ++i) { accum_indices->push_back(i); print_recursive(dimensions.subspan(1), accum_indices); accum_indices->pop_back(); if (i < dimensions[0] - 1) { printer->Append(","); printer->Append(dimensions.size() > 1 ? linebreak : " "); } } printer->Append(brace_to_string("}")); } }; auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; void PrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); CHECK(LayoutUtil::HasLayout(literal.shape())); CHECK(LayoutUtil::HasLayout(subshape)); if (subshape.IsTuple()) { TuplePrintHelper(literal, shape_index, print_shape, print_layout, oneline, printer); } else if (subshape.IsToken()) { printer->Append("token"); } else { CHECK(LayoutUtil::IsDenseArray(subshape)); if (literal.IsKnown(shape_index)) { DenseArrayPrintHelper(literal, shape_index, print_shape, print_layout, oneline, printer); } else { PrintShape(print_layout, subshape, printer); printer->Append(" "); if (literal.IsDetermined(shape_index)) { printer->Append("unknown"); } else { printer->Append("undetermined"); } } } } void LiteralBase::Print(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/false, /*oneline=*/false, printer); } void LiteralBase::PrintOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/false, /*oneline=*/true, printer); } void LiteralBase::PrintWithoutShape(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/false, /*print_layout=*/false, /*oneline=*/false, printer); } void LiteralBase::PrintWithoutShapeOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/false, /*print_layout=*/false, /*oneline=*/true, printer); } void LiteralBase::PrintWithLayout(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/true, /*oneline=*/false, printer); } void LiteralBase::PrintWithLayoutOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/true, /*oneline=*/true, printer); } std::string LiteralBase::ToString() const { StringPrinter printer; Print(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringOneline() const { StringPrinter printer; PrintOneline(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithoutShape() const { StringPrinter printer; PrintWithoutShape(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithoutShapeOneline() const { StringPrinter printer; PrintWithoutShapeOneline(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithLayout() const { StringPrinter printer; PrintWithLayout(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithLayoutOneline() const { StringPrinter printer; PrintWithLayoutOneline(&printer); return std::move(printer).ToString(); } void LiteralBase::EachCellAsString( absl::FunctionRef<void(absl::Span<const int64_t> indices, const std::string& value)> per_cell) const { if (ShapeUtil::IsZeroElementArray(shape())) { return; } auto indices = IndexUtil::LinearIndexToMultidimensionalIndex( shape(), /*linear_index=*/0); do { per_cell(indices, GetAsString(indices)); } while (IndexUtil::BumpIndices(shape(), absl::MakeSpan(indices))); } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { absl::StatusOr<Literal> ConvertSwitch(const LiteralBase& literal, PrimitiveType primitive_dest_type) { TF_RET_CHECK(LayoutUtil::IsDenseArray(literal.shape())); if (literal.shape().element_type() == primitive_dest_type) { return literal.Clone(); } // Source Array type requirement is ensured by IsDenseArray before. if (!primitive_util::IsArrayType(primitive_dest_type) || !primitive_util::IsArrayType(literal.shape().element_type())) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(literal.shape().element_type()), PrimitiveType_Name(primitive_dest_type)); } // At this point, we know both src & dst are array types, while src is not // complex type, so we can allocate the result literal here to avoid // duplicating it N^2 times in the conversion implementation. Literal result( ShapeUtil::ChangeElementType(literal.shape(), primitive_dest_type)); TF_RETURN_IF_ERROR(primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { return ConvertIfDestTypeMatches<primitive_type_constant>(literal, result); }, literal.shape().element_type())); return result; } absl::StatusOr<Literal> LiteralBase::Convert( PrimitiveType primitive_dest_type) const { return ConvertSwitch(*this, primitive_dest_type); } absl::StatusOr<Literal> LiteralBase::BitcastConvert( const Shape& dest_shape) const { if (ShapeUtil::ByteSizeOf(dest_shape) != ShapeUtil::ByteSizeOf(shape())) { return InvalidArgument( "Can not bitcast-convert from shape %s to a shape of different size %s", shape().ToString(), dest_shape.ToString()); } if (dest_shape.IsTuple() || shape().IsTuple()) { return InvalidArgument( "bitcast-convert is not valid for tuple shapes %s->%s", shape().ToString(), dest_shape.ToString()); } if (shape().is_dynamic() || dest_shape.is_dynamic()) { return InvalidArgument( "bitcast-convert is not valid for dynamic shape %s->%s", shape().ToString(), dest_shape.ToString()); } Literal out(dest_shape); std::memcpy(out.root_piece_.buffer(), root_piece().buffer(), root_piece().size_bytes_dense()); // Perform the reshape on little endian encoding even on big endian machines. if constexpr (!kLittleEndian) { // Swap byte ordering as per the input data type. size_t input_elem_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); TF_RETURN_IF_ERROR(tsl::ByteSwapArray( const_cast<char*>(out.root_piece().buffer()), input_elem_size, out.root_piece().size_bytes_dense() / input_elem_size)); // Swap byte ordering as per the output data type. size_t output_elem_size = ShapeUtil::ByteSizeOfPrimitiveType(dest_shape.element_type()); TF_RETURN_IF_ERROR(tsl::ByteSwapArray( const_cast<char*>(out.root_piece().buffer()), output_elem_size, out.root_piece().size_bytes_dense() / output_elem_size)); } return out; } absl::StatusOr<Literal> LiteralBase::ConvertToShape( const Shape& dest_shape) const { if (!dest_shape.IsTuple()) { return Convert(dest_shape.element_type()); } std::vector<Literal> elements; const auto tuple_element_count = ShapeUtil::TupleElementCount(shape()); elements.reserve(tuple_element_count); for (int i = 0; i < tuple_element_count; ++i) { auto element = LiteralSlice(*this, {i}); TF_ASSIGN_OR_RETURN( auto new_element, element.ConvertToShape(ShapeUtil::GetSubshape(dest_shape, {i}))); elements.push_back(std::move(new_element)); } return MutableLiteralBase::MoveIntoTuple(absl::MakeSpan(elements)); } /* static */ Literal MutableLiteralBase::MoveIntoTuple( absl::Span<Literal> elements) { std::vector<const Shape*> element_shapes; element_shapes.reserve(elements.size()); for (const Literal& element : elements) { element_shapes.push_back(&element.shape()); } Literal literal(ShapeUtil::MakeTupleShapeWithPtrs(element_shapes), /*allocate_arrays=*/false); for (int i = 0, end = elements.size(); i < end; ++i) { TF_CHECK_OK( literal.MoveFrom(std::move(elements[i]), /*dest_shape_index=*/{i})); } return literal; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualDynamicSize( const LiteralBase::Piece& other) const { DCHECK(ShapeUtil::Compatible(subshape(), other.subshape())); if (subshape().is_static()) { return true; } for (int64_t i = 0; i < subshape().rank(); ++i) { if (GetDynamicSize(i) != other.GetDynamicSize(i)) { return false; } } return true; } bool LiteralBase::Piece::EqualElements(const LiteralBase::Piece& other) const { if (subshape().is_static() && ShapeUtil::Equal(subshape(), other.subshape()) && subshape().IsArray()) { CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(size_bytes_dense(), other.size_bytes_dense()); if (primitive_util::IsSubByteNonPredType(subshape().element_type())) { CHECK(!primitive_util::IsFloatingPointType(subshape().element_type())); auto one_array = buffer(); auto two_array = other.buffer(); const int bits_per_element = primitive_util::BitWidth(subshape().element_type()); const uint8_t mask = LsbMask<uint8_t>(bits_per_element); for (int64_t i = 0; i < size_bytes_dense(); ++i) { if ((one_array[i] & mask) != (two_array[i] & mask)) return false; } return true; } return memcmp(buffer(), other.buffer(), size_bytes_dense()) == 0; } std::vector<int64_t> multi_index; return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeSrcT = NativeTypeOf<primitive_type_constant>; return EqualElementsInternal<NativeSrcT>(other, &multi_index); }, subshape().element_type()); } bool LiteralBase::Equal(const LiteralBase& other, bool layout_sensitive) const { // Checking the structure of tuple literals. Checks for dense arrays are // performed below. if (!ShapeUtil::EqualStructure(shape(), other.shape())) { return false; } return root_piece().ForEachSubpieceWithBool([&](const ShapeIndex& index, const Piece& piece) { const Piece& other_piece = other.piece(index); const Shape& subshape = piece.subshape(); const Shape& other_subshape = other_piece.subshape(); if (subshape.element_type() != other_subshape.element_type()) { return false; } if (!piece.subshape().IsArray()) { return true; } if (subshape.rank() != other_subshape.rank()) { return false; } if (layout_sensitive && (subshape.layout() != other_subshape.layout())) { return false; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (piece.GetDynamicSize(i) != other_piece.GetDynamicSize(i)) { return false; } } if (!piece.EqualElements(other_piece)) { return false; } return true; }); } return root_piece().ForEachSubpieceWithBool([&](const ShapeIndex& index, const Piece& piece) { const Piece& other_piece = other.piece(index); const Shape& subshape = piece.subshape(); const Shape& other_subshape = other_piece.subshape(); if (subshape.element_type() != other_subshape.element_type()) { return false; } if (!piece.subshape().IsArray()) { return true; } if (subshape.rank() != other_subshape.rank()) { return false; } if (layout_sensitive && (subshape.layout() != other_subshape.layout())) { return false; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (piece.GetDynamicSize(i) != other_piece.GetDynamicSize(i)) { return false; } } if (!piece.EqualElements(other_piece)) { return false; } return true; }); static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(std::complex<T> a, std::complex<T> b) { return EqualIncludingNan(a.real(), b.real()) && EqualIncludingNan(a.imag(), b.imag()); } static bool EqualIncludingNan(std::complex<T> a, std::complex<T> b) { return EqualIncludingNan(a.real(), b.real()) && EqualIncludingNan(a.imag(), b.imag()); } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } bool Literal::Piece::IsAll(const Literal& scalar) const { CHECK(ShapeUtil::IsScalar(scalar.shape())) << scalar.shape().ToString(); if (!subshape().IsArray()) { return false; } CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(subshape().element_type(), scalar.shape().element_type()); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, subshape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, int64_t Literal::Piece::CountAll(const Literal& scalar) const { CHECK(ShapeUtil::IsScalar(scalar.shape())) << scalar.shape().ToString(); if (!subshape().IsArray()) { return 0; } CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(subshape().element_type(), scalar.shape().element_type()); return primitive_util::ArrayTypeSwitch<int64_t>( [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, subshape().element_type()); } [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { bool LiteralBase::IsAll(const Literal& scalar) const { return root_piece().IsAll(scalar); } bool LiteralBase::IsAll(int8_t value) const { if (!shape().IsArray()) { return false; } PrimitiveType ty = shape().element_type(); if (primitive_util::IsFloatingPointType(ty)) { return IsAllFloatImpl(value, /*round_value=*/false); } if (primitive_util::IsUnsignedIntegralType(ty) && value < 0) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllFloat(float value) const { return IsAllFloatImpl(value, /*round_value=*/true); } bool LiteralBase::IsAllFloatImpl(float value, bool round_value) const { PrimitiveType ty = shape().element_type(); if (!primitive_util::IsFloatingPointType(ty)) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::FloatingPointTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllComplex(complex64 value) const { PrimitiveType ty = shape().element_type(); if (!primitive_util::IsComplexType(ty)) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::ComplexTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllFirst() const { if (!shape().IsArray()) { return false; } // Empty shapes are not all the first element since there is no first element. if (ShapeUtil::IsZeroElementArray(shape())) { return false; } absl::InlinedVector<int64_t, 4> start_indices(/*n=*/shape().rank(), 0); absl::InlinedVector<int64_t, 4> end_indices(/*n=*/shape().rank(), 1); Literal first = Slice(start_indices, end_indices); return IsAll(first.Reshape({}).value()); } bool LiteralBase::IsR1Iota() const { if (!shape().IsArray()) { return false; } CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); if (shape().rank() != 1) { return false; } return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, shape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, std::optional<int64_t> LiteralBase::IsR1StridedIota() const { if (!shape().IsArray() || shape().rank() != 1) { return std::nullopt; } CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); const int64_t elements = ShapeUtil::ElementsIn(shape()); const PrimitiveType type = shape().element_type(); if (elements <= 1 || !primitive_util::IsIntegralType(type)) { return std::nullopt; } return primitive_util::IntegralTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, bool LiteralBase::IsZero(absl::Span<const int64_t> indices) const { CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, shape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void LiteralBase::Piece::set_array_value_state(ArrayValueState state) { array_value_state_ = state; } LiteralBase::ArrayValueState LiteralBase::Piece::get_array_value_state() const { return array_value_state_; } void LiteralBase::Piece::WriteToProto(LiteralProto* proto) const { *proto->mutable_shape() = subshape().ToProto(); switch (subshape().element_type()) { case PRED: CopyToRepeatedField(proto->mutable_preds(), data<bool>()); break; case U2: *proto->mutable_u2s() = std::string( reinterpret_cast<const char*>(data<u2>().data()), size_bytes_dense()); break; case U4: *proto->mutable_u4s() = std::string( reinterpret_cast<const char*>(data<u4>().data()), size_bytes_dense()); break; case U8: proto->set_u8s(static_cast<const unsigned char*>(data<uint8_t>().data()), element_count()); break; case U16: *proto->mutable_u16s() = std::string(reinterpret_cast<const char*>(data<uint16_t>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_u16s()); } break; case U32: CopyToRepeatedField(proto->mutable_u32s(), data<uint32_t>()); break; case U64: CopyToRepeatedField(proto->mutable_u64s(), data<uint64_t>()); break; case S2: *proto->mutable_s2s() = std::string( reinterpret_cast<const char*>(data<s2>().data()), size_bytes_dense()); break; case S4: *proto->mutable_s4s() = std::string( reinterpret_cast<const char*>(data<s4>().data()), size_bytes_dense()); break; case S8: proto->set_s8s(static_cast<const signed char*>(data<int8_t>().data()), element_count()); break; case S16: *proto->mutable_s16s() = std::string(reinterpret_cast<const char*>(data<int16_t>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_s16s()); } break; case S32: CopyToRepeatedField(proto->mutable_s32s(), data<int32_t>()); break; case S64: CopyToRepeatedField(proto->mutable_s64s(), data<int64_t>()); break; case F8E5M2: *proto->mutable_f8e5m2s() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e5m2>().data()), size_bytes_dense()); break; case F8E4M3FN: *proto->mutable_f8e4m3fns() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3fn>().data()), size_bytes_dense()); break; case F8E4M3B11FNUZ: *proto->mutable_f8e4m3b11fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3b11fnuz>().data()), size_bytes_dense()); break; case F8E5M2FNUZ: *proto->mutable_f8e5m2fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e5m2fnuz>().data()), size_bytes_dense()); break; case F8E4M3FNUZ: *proto->mutable_f8e4m3fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3fnuz>().data()), size_bytes_dense()); break; case F16: *proto->mutable_f16s() = std::string(reinterpret_cast<const char*>(data<half>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_f16s()); } break; case BF16: *proto->mutable_bf16s() = std::string(reinterpret_cast<const char*>(data<bfloat16>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_bf16s()); } break; case F32: CopyToRepeatedField(proto->mutable_f32s(), data<float>()); break; case F64: CopyToRepeatedField(proto->mutable_f64s(), data<double>()); break; case C64: for (complex64 value : data<complex64>()) { proto->add_c64s(value.real()); proto->add_c64s(value.imag()); } break; case C128: for (complex128 value : data<complex128>()) { proto->add_c128s(value.real()); proto->add_c128s(value.imag()); } break; case TUPLE: case TOKEN: // Nothing to do but assign the shape which is done above. return; default: // TODO(b/111551621): Support serializing more PrimitiveTypes. LOG(FATAL) << "Unhandled primitive type " << PrimitiveType_Name(subshape().element_type()); } } const void* LiteralBase::Piece::untyped_data() const { DCHECK(LayoutUtil::IsDenseArray(subshape())) << ShapeUtil::HumanString(subshape()); return buffer(); } void* LiteralBase::Piece::untyped_data() { DCHECK(LayoutUtil::IsDenseArray(subshape())) << ShapeUtil::HumanString(subshape()); return buffer(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status LiteralBase::Piece::CopyFromProto(const LiteralProto& proto) { // These conditions should have been checked in // MutableLiteralBase::CreateFromProto. TF_RET_CHECK(proto.has_shape()); Shape shape(proto.shape()); TF_RET_CHECK(LayoutUtil::HasLayout(shape)); TF_RET_CHECK(ShapeUtil::Equal(shape, subshape())); switch (subshape().element_type()) { case PRED: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<bool>(), proto.preds())); break; case S2: { const std::string& s(proto.s2s()); TF_RET_CHECK(data<s2>().size() * sizeof(s2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case S4: { const std::string& s(proto.s4s()); TF_RET_CHECK(data<s4>().size() * sizeof(s4) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case S8: { auto s8_data = data<int8_t>(); TF_RET_CHECK(proto.s8s().size() == s8_data.size()); std::copy(proto.s8s().begin(), proto.s8s().end(), s8_data.begin()); break; } case S16: { const std::string& s(proto.s16s()); TF_RET_CHECK(data<int16_t>().size() * sizeof(int16_t) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case S32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<int32_t>(), proto.s32s())); break; case S64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<int64_t>(), proto.s64s())); break; case U2: { const std::string& s(proto.u2s()); TF_RET_CHECK(data<u2>().size() * sizeof(u2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case U4: { const std::string& s(proto.u4s()); TF_RET_CHECK(data<u4>().size() * sizeof(u4) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case U8: { auto u8_data = data<uint8_t>(); TF_RET_CHECK(proto.u8s().size() == u8_data.size()); std::copy(proto.u8s().begin(), proto.u8s().end(), u8_data.begin()); break; } case U16: { const std::string& s(proto.u16s()); TF_RET_CHECK(data<uint16_t>().size() * sizeof(uint16_t) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case U32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<uint32_t>(), proto.u32s())); break; case U64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<uint64_t>(), proto.u64s())); break; case F8E5M2: { const std::string& s(proto.f8e5m2s()); TF_RET_CHECK(data<tsl::float8_e5m2>().size() * sizeof(tsl::float8_e5m2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3FN: { const std::string& s(proto.f8e4m3fns()); TF_RET_CHECK(data<tsl::float8_e4m3fn>().size() * sizeof(tsl::float8_e4m3fn) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3B11FNUZ: { const std::string& s(proto.f8e4m3b11fnuzs()); TF_RET_CHECK(data<tsl::float8_e4m3b11fnuz>().size() * sizeof(tsl::float8_e4m3b11fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E5M2FNUZ: { const std::string& s(proto.f8e5m2fnuzs()); TF_RET_CHECK(data<tsl::float8_e5m2fnuz>().size() * sizeof(tsl::float8_e5m2fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3FNUZ: { const std::string& s(proto.f8e4m3fnuzs()); TF_RET_CHECK(data<tsl::float8_e4m3fnuz>().size() * sizeof(tsl::float8_e4m3fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F16: { const std::string& s(proto.f16s()); TF_RET_CHECK(data<half>().size() * sizeof(half) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case BF16: { const std::string& s(proto.bf16s()); TF_RET_CHECK(data<bfloat16>().size() * sizeof(bfloat16) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case F32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<float>(), proto.f32s())); break; case F64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<double>(), proto.f64s())); break; case C64: { auto complex_data = data<complex64>(); TF_RET_CHECK(proto.c64s_size() == complex_data.size() * 2); for (int64_t i = 0; i < complex_data.size(); ++i) { complex_data[i] = complex64{proto.c64s(i * 2), proto.c64s(i * 2 + 1)}; } break; } case C128: { auto complex_data = data<complex128>(); const int64_t complex_data_size_doubled = complex_data.size() * 2; TF_RET_CHECK(proto.c128s_size() == complex_data_size_doubled); for (int64_t i = 0, end = complex_data.size(); i < end; ++i) { complex_data[i] = complex128{proto.c128s(i * 2), proto.c128s(i * 2 + 1)}; } break; } case TUPLE: return InvalidArgument("Should not be called on tuple shapes: %s", ShapeUtil::HumanString(subshape())); default: return InvalidArgument("Is called on unsupported shape: %s", ShapeUtil::HumanString(subshape())); } return absl::OkStatus(); } bool LiteralBase::Piece::IsKnown() const { if (array_value_state_ != ArrayValueState::kKnown) { return false; } if (subshape().IsTuple()) { bool are_all_leaf_arrays_known = true; ForEachSubpiece([&are_all_leaf_arrays_known](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_known &= piece.IsKnown(); }); return are_all_leaf_arrays_known; } return true; } ForEachSubpiece([&are_all_leaf_arrays_known](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_known &= piece.IsKnown(); }); bool LiteralBase::Piece::IsDetermined() const { if (array_value_state_ == ArrayValueState::kUndetermined) { return false; } if (subshape().IsTuple()) { bool are_all_leaf_arrays_determined = true; ForEachSubpiece([&are_all_leaf_arrays_determined](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_determined &= piece.IsDetermined(); }); return are_all_leaf_arrays_determined; } return true; } ForEachSubpiece([&are_all_leaf_arrays_determined](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_determined &= piece.IsDetermined(); }); LiteralProto LiteralBase::ToProto() const { LiteralProto proto; root_piece().ForEachSubpiece( [&](const ShapeIndex& index, const Piece& piece) { LiteralProto* proto_piece = &proto; for (int64_t i : index) { while (proto_piece->tuple_literals_size() <= i) { proto_piece->add_tuple_literals(); } proto_piece = proto_piece->mutable_tuple_literals(i); } piece.WriteToProto(proto_piece); }); return proto; } [&](const ShapeIndex& index, const Piece& piece) { LiteralProto* proto_piece = &proto; for (int64_t i : index) { while (proto_piece->tuple_literals_size() <= i) { proto_piece->add_tuple_literals(); } proto_piece = proto_piece->mutable_tuple_literals(i); } piece.WriteToProto(proto_piece); }); const void* LiteralBase::untyped_data(const ShapeIndex& shape_index) const { return piece(shape_index).untyped_data(); } void* MutableLiteralBase::untyped_data(const ShapeIndex& shape_index) { return piece(shape_index).untyped_data(); } int64_t LiteralBase::size_bytes(const ShapeIndex& shape_index) const { return piece(shape_index).size_bytes_dense(); } std::string LiteralBase::GetR1U8AsString() const { CHECK(shape().IsArray()); CHECK_EQ(shape().rank(), 1); CHECK_EQ(shape().element_type(), U8); return std::string(absl::bit_cast<const char*>(data<uint8_t>().data()), ShapeUtil::ElementsIn(shape())); } void MutableBorrowingLiteral::CopyPieceSubtree(const Shape& shape, const Piece* src_piece, Piece* dest_piece) { DCHECK(ShapeUtil::Equal(src_piece->subshape(), dest_piece->subshape())) << "src_piece has shape: " << ShapeUtil::HumanString(src_piece->subshape()) << "dest_piece has shape: " << ShapeUtil::HumanString(dest_piece->subshape()); dest_piece->set_array_value_state(src_piece->get_array_value_state()); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); Piece child_piece; child_piece.set_subshape(&subshape); CopyPieceSubtree(subshape, &src_piece->child(i), &child_piece); dest_piece->emplace_back(std::move(child_piece)); } } else if (shape.IsArray()) { dest_piece->set_buffer(const_cast<char*>(src_piece->buffer())); } } MutableLiteralBase::~MutableLiteralBase() = default; MutableBorrowingLiteral::MutableBorrowingLiteral( const MutableBorrowingLiteral& literal) : MutableLiteralBase() { shape_ = literal.shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.root_piece(), root_piece_); } MutableBorrowingLiteral& MutableBorrowingLiteral::operator=( const MutableBorrowingLiteral& literal) { shape_ = literal.shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.root_piece(), root_piece_); return *this; } MutableBorrowingLiteral::MutableBorrowingLiteral(MutableLiteralBase* literal) : MutableLiteralBase() { shape_ = literal->shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal->root_piece(), root_piece_); } MutableBorrowingLiteral::MutableBorrowingLiteral( MutableBorrowingLiteral literal, const ShapeIndex& view_root) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(literal.piece(view_root).subshape()); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.piece(view_root), root_piece_); } MutableBorrowingLiteral::MutableBorrowingLiteral(const char* src_buf_ptr, const Shape& shape) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(shape); CHECK(LayoutUtil::HasLayout(*shape_)); CHECK(!shape_->IsTuple()); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); root_piece_->set_buffer(const_cast<char*>(src_buf_ptr)); } MutableBorrowingLiteral::MutableBorrowingLiteral(absl::Span<char*> src_buf_ptrs, const Shape& shape) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(shape); if (!shape_->IsTuple()) { CHECK_EQ(src_buf_ptrs.size(), 1); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); root_piece_->set_buffer(const_cast<char*>(src_buf_ptrs[0])); } else { CHECK(!ShapeUtil::IsNestedTuple(*shape_)); CHECK_EQ(src_buf_ptrs.size(), ShapeUtil::TupleElementCount(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); for (int i = 0; i < src_buf_ptrs.size(); ++i) { Piece child_piece; const auto& src_shape = shape_->tuple_shapes(i); CHECK(src_shape.IsArray()); child_piece.set_subshape(&src_shape); child_piece.set_buffer(src_buf_ptrs[i]); root_piece_->emplace_back(std::move(child_piece)); } } } MutableBorrowingLiteral::MutableBorrowingLiteral(ShapeTree<char*> src_buf_ptrs) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(src_buf_ptrs.shape()); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); BuildPieceSubtree(*shape_, root_piece_); root_piece_->ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); } [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); MutableBorrowingLiteral::~MutableBorrowingLiteral() { if (root_piece_ != nullptr) { delete root_piece_; } } LiteralSlice::LiteralSlice(const LiteralBase& literal) : LiteralBase(), root_piece_(&literal.root_piece()) {} LiteralSlice::LiteralSlice(const LiteralBase& literal, const ShapeIndex& view_root) : LiteralBase(), root_piece_(&literal.piece(view_root)) {} BorrowingLiteral::BorrowingLiteral(const char* src_buf_ptr, const Shape& shape) : LiteralBase(), shape_(std::make_unique<Shape>(shape)) { CHECK(shape_->IsArray()); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); root_piece_.set_buffer(const_cast<char*>(src_buf_ptr)); } BorrowingLiteral::BorrowingLiteral(absl::Span<const char* const> src_buf_ptrs, const Shape& shape) : LiteralBase(), shape_(std::make_unique<Shape>(shape)) { CHECK(shape_->IsTuple()); CHECK(!ShapeUtil::IsNestedTuple(*shape_)); CHECK_EQ(src_buf_ptrs.size(), ShapeUtil::TupleElementCount(*shape_)); root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); BuildPieceSubtree(*shape_, &root_piece_); for (int i = 0, end = src_buf_ptrs.size(); i < end; ++i) { const auto& src_shape = shape_->tuple_shapes(i); CHECK(src_shape.IsArray()); root_piece_.child(i).set_buffer(const_cast<char*>(src_buf_ptrs[i])); } } BorrowingLiteral::BorrowingLiteral(ShapeTree<const char*> src_buf_ptrs) : LiteralBase(), shape_(std::make_unique<Shape>(src_buf_ptrs.shape())) { root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); BuildPieceSubtree(*shape_, &root_piece_); root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); } [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); });
#include "xla/literal.h" #include <algorithm> #include <cmath> #include <complex> #include <cstdint> #include <functional> #include <limits> #include <random> #include <string> #include <tuple> #include <utility> #include <vector> #include "absl/base/casts.h" #include "absl/hash/hash.h" #include "absl/random/random.h" #include "absl/status/status.h" #include "absl/strings/match.h" #include "absl/types/span.h" #include "xla/array.h" #include "xla/array2d.h" #include "xla/array3d.h" #include "xla/array4d.h" #include "xla/index_util.h" #include "xla/layout.h" #include "xla/layout_util.h" #include "xla/literal_util.h" #include "xla/primitive_util.h" #include "xla/shape.h" #include "xla/shape_tree.h" #include "xla/shape_util.h" #include "xla/test.h" #include "xla/types.h" #include "xla/util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/errors.h" #include "tsl/platform/logging.h" // IWYU pragma: keep #include "tsl/platform/macros.h" #include "tsl/platform/ml_dtypes.h" #include "tsl/platform/statusor.h" #include "tsl/platform/test_benchmark.h" class LiteralUtilTest : public ::testing::Test { protected: LiteralUtilTest() { Array4D<float> arr4d({ // clang-format off { // i0=0 { // i1=0 {1, 2, 3}, // i2=0 {4, 5, 6}, // i2=1 {7, 8, 9}, // i2=2 }, { // i1=1 {11, 12, 13}, {14, 15, 16}, {17, 18, 19}, }, }, { // i0=1 { // i1=0 {101, 102, 103}, {104, 105, 106}, {107, 108, 109}, }, { // i1=1 {201, 202, 203}, // i2=0 {204, 205, 206}, // i2=1 {207, 208, 209}, // i2=2 }, }, // clang-format on }); layout_r2_dim0major_ = LayoutUtil::MakeLayout({1, 0}); layout_r2_dim0minor_ = LayoutUtil::MakeLayout({0, 1}); layout_r3_dim0major_ = LayoutUtil::MakeLayout({2, 1, 0}); layout_r3_dim0minor_ = LayoutUtil::MakeLayout({0, 1, 2}); layout_r4_dim0major_ = LayoutUtil::MakeLayout({3, 2, 1, 0}); layout_r4_dim0minor_ = LayoutUtil::MakeLayout({0, 1, 2, 3}); literal_r4_2x2x3x3_dim0major_ = LiteralUtil::CreateR4FromArray4DWithLayout<float>(arr4d, layout_r4_dim0major_); literal_r4_2x2x3x3_dim0minor_ = LiteralUtil::CreateR4FromArray4DWithLayout<float>(arr4d, layout_r4_dim0minor_); } Layout layout_r2_dim0major_; Layout layout_r2_dim0minor_; Layout layout_r3_dim0major_; Layout layout_r3_dim0minor_; Layout layout_r4_dim0major_; Layout layout_r4_dim0minor_; Literal literal_r4_2x2x3x3_dim0major_; Literal literal_r4_2x2x3x3_dim0minor_; }; TEST_F(LiteralUtilTest, CopyBetweenSameTuple) { Literal elements[] = {LiteralUtil::CreateR0<int32_t>(-2), LiteralUtil::CreateR0<int32_t>(4)}; Literal tuple = LiteralUtil::MakeTuple({&elements[0], &elements[1]}); EXPECT_EQ(tuple.Get<int32_t>({}, {0}), -2); EXPECT_EQ(tuple.Get<int32_t>({}, {1}), 4); // Copy from one element to the other. TF_ASSERT_OK(tuple.CopyFrom(tuple, /*dest_shape_index=*/{1}, /*src_shape_index=*/{0})); EXPECT_EQ(tuple.Get<int32_t>({}, {0}), -2); EXPECT_EQ(tuple.Get<int32_t>({}, {1}), -2); }
LiteralUtilTest_CopyFromAndToZeroElement
xla/literal_test.cc
bool LiteralProtoHasValues(const LiteralProto& proto) { return !proto.s2s().empty() || !proto.s4s().empty() || !proto.s8s().empty() || !proto.s16s().empty() || proto.s32s_size() || proto.s64s_size() || !proto.u2s().empty() || !proto.u4s().empty() || !proto.u8s().empty() || !proto.u16s().empty() || proto.u32s_size() || proto.u64s_size() || !proto.f8e5m2s().empty() || !proto.f8e4m3fns().empty() || !proto.f8e4m3b11fnuzs().empty() || !proto.f8e5m2fnuzs().empty() || !proto.f8e4m3fnuzs().empty() || !proto.f16s().empty() || !proto.bf16s().empty() || proto.f32s_size() || proto.f64s_size() || proto.c64s_size() || proto.c128s_size() || proto.preds_size() || proto.tuple_literals_size(); } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { const Shape& NilShape() { static const Shape* shape = new Shape(TUPLE, {}, {}, {}); return *shape; } const Shape* TryInternShape(const Shape& shape) { if (shape.IsTuple() && shape.tuple_shapes_size() == 0) { return &NilShape(); } if (shape.IsArray() && shape.dimensions_size() == 0 && shape.is_static() && shape.layout().tiles_size() == 0 && shape.layout().memory_space() == 0) { return &ScalarShape(shape.element_type()); } return nullptr; } StrideConfig::StrideConfig(const Shape& source_shape, const Shape& dest_shape, absl::Span<const int64_t> dimensions) : dimensions(dimensions), base(dimensions.size(), 0), step(dimensions.size(), 1) { if (!dimensions.empty()) { // Selects the shape with the largest minor dimension as the one upon // which to run the tight stride loop. if (dimensions[LayoutUtil::Minor(source_shape.layout(), 0)] >= dimensions[LayoutUtil::Minor(dest_shape.layout(), 0)]) { minor_dimension = LayoutUtil::Minor(source_shape.layout(), 0); dest_stride = IndexUtil::GetDimensionStride(dest_shape, minor_dimension); } else { minor_dimension = LayoutUtil::Minor(dest_shape.layout(), 0); source_stride = IndexUtil::GetDimensionStride(source_shape, minor_dimension); } minor_loop_size = dimensions[minor_dimension]; step[minor_dimension] = minor_loop_size; } } LiteralBase::~LiteralBase() = default; const Shape& LiteralBase::shape() const { return root_piece().subshape(); } const char* LiteralBase::Piece::buffer() const { // std::visit is avoided here due to its code size issues. if (auto* r = std::get_if<DenseRep>(&rep_)) { return r->data; } if (auto* r = std::get_if<DenseInlinedRep>(&rep_)) { return r->data; } DCHECK(std::holds_alternative<TupleRep>(rep_) || std::holds_alternative<Uninitialized>(rep_)); return nullptr; } const LiteralBase::Piece& LiteralBase::piece( const ShapeIndex& shape_index) const { const Piece* piece = &root_piece(); for (const auto i : shape_index) { DCHECK_GE(i, 0); DCHECK_LT(i, piece->children_size()); piece = &piece->child(i); } return *piece; } std::ostream& operator<<(std::ostream& out, const Literal& literal) { out << literal.ToString(); return out; } Shape* MutableLiteralBase::mutable_shape_do_not_use() { const Shape* const_shape = shape_.get(); if (!shape_.OwnsPtr()) { shape_ = MaybeOwningShapePtr(std::make_unique<Shape>(*shape_)); } Shape* shape = shape_.get_mutable(); if (shape != const_shape) { std::function<void(const Shape&, Piece*)> set_piece_shapes = [&set_piece_shapes](const Shape& shape, Piece* piece) { piece->set_subshape(&shape); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); set_piece_shapes(subshape, &piece->child(i)); } } }; set_piece_shapes(*shape, &mutable_root_piece()); } return shape; } [&set_piece_shapes](const Shape& shape, Piece* piece) { piece->set_subshape(&shape); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); set_piece_shapes(subshape, &piece->child(i)); } } }; Literal::Literal() : Literal(NilShape()) {} Literal::Literal(const Shape& shape) : Literal(shape, /*allocate_arrays=*/true) {} void Literal::SetShape(const Shape& shape) { Shape shape_storage; const Shape* shape_ptr = &shape; if (LayoutUtil::HasCustomElementSizeInBits(shape)) { shape_storage = shape; shape_storage.mutable_layout()->set_element_size_in_bits(0); shape_ptr = &shape_storage; } if (const Shape* intered_shape_ptr = TryInternShape(*shape_ptr)) { shape_ = intered_shape_ptr; } else { shape_ = std::make_unique<Shape>(*shape_ptr); } } void Literal::SetPiece(const Shape& shape, Piece* piece, bool allocate_arrays, ArrayValueState leaf_array_value_state) { if (shape.IsTuple()) { for (const Shape& subshape : shape.tuple_shapes()) { Piece child_piece; child_piece.set_subshape(&subshape); SetPiece(subshape, &child_piece, allocate_arrays, leaf_array_value_state); piece->emplace_back(std::move(child_piece)); } } else if (shape.IsArray()) { DCHECK(LayoutUtil::IsDenseArray(shape)) << "literal array storage is currently only supported for dense " "arrays: " << shape; piece->set_array_value_state(leaf_array_value_state); if (leaf_array_value_state == LiteralBase::ArrayValueState::kKnown && allocate_arrays) { piece->AllocateBuffers(); } } } Literal::Literal(const Shape& shape, bool allocate_arrays, ArrayValueState leaf_array_value_state) : MutableLiteralBase() { SetShape(shape); CHECK(leaf_array_value_state != ArrayValueState::kKnown || LayoutUtil::HasLayout(*shape_)); root_piece_.set_subshape(shape_.get()); CHECK(&root_piece_.subshape() == shape_.get()); SetPiece(*shape_, &root_piece_, allocate_arrays, leaf_array_value_state); } Literal::~Literal() { DeallocateBuffers(); } void Literal::DeallocateBuffers() { root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { piece->DeallocateBuffers(); }); } Literal::Literal(Literal&& other) : MutableLiteralBase() { *this = std::move(other); } Literal& Literal::operator=(Literal&& other) { DCHECK(&other.root_piece_.subshape() == other.shape_.get()); using std::swap; swap(shape_, other.shape_); swap(root_piece_, other.root_piece_); DCHECK(&root_piece_.subshape() == shape_.get()); return *this; } Literal LiteralBase::CreateFromShape(const Shape& shape) { Literal literal(shape); literal.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (piece->subshape().IsArray()) { memset(piece->untyped_data(), 0, piece->size_bytes_dense()); } }); return literal; } [&](const ShapeIndex& index, Piece* piece) { if (piece->subshape().IsArray()) { memset(piece->untyped_data(), 0, piece->size_bytes_dense()); } }); Literal LiteralBase::CreateFromShapeWithUnknownLeafArrays(const Shape& shape) { Literal literal(shape, /*allocate_arrays=*/false, ArrayValueState::kUnknown); return literal; } Literal LiteralBase::CreateFromShapeWithUndeterminedLeafArrays( const Shape& shape) { Literal literal(shape, /*allocate_arrays=*/false, ArrayValueState::kUndetermined); return literal; } int32_t LiteralBase::GetDynamicSize(int64_t dim_index) const { return GetDynamicSize(dim_index, {}); } int32_t LiteralBase::GetDynamicSize(int64_t dim_index, const ShapeIndex& shape_index) const { return piece(shape_index).GetDynamicSize(dim_index); } std::optional<int64_t> LiteralBase::GetFirstInteger() const { if (!primitive_util::IsIntegralType(shape().element_type())) { return std::nullopt; } return primitive_util::IntegralTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, void LiteralBase::BuildPieceSubtree(const Shape& shape, Piece* piece) { CHECK(shape.IsTuple()); for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); Piece child_piece; child_piece.set_subshape(&subshape); if (subshape.IsTuple()) { BuildPieceSubtree(subshape, &child_piece); } piece->emplace_back(std::move(child_piece)); } } absl::Status LiteralBase::SerializeToString(std::string* output) const { ShapeProto shape_proto = shape().ToProto(); TF_ASSIGN_OR_RETURN(int64_t size, ShapeUtil::SerializedSizeWithProto(shape(), shape_proto)); output->resize(size); return SerializeWithShapeProto(shape_proto, output->data()); } absl::StatusOr<std::string> LiteralBase::SerializeAsString() const { std::string result; TF_RETURN_IF_ERROR(SerializeToString(&result)); return std::move(result); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { void MutableLiteralBase::CopyElementFrom(const LiteralSlice& src_literal, absl::Span<const int64_t> src_index, absl::Span<const int64_t> dest_index) { DCHECK(LayoutUtil::IsDenseArray(shape())); DCHECK_EQ(shape().element_type(), src_literal.shape().element_type()); const int64_t src_linear_index = IndexUtil::MultidimensionalIndexToLinearIndex(src_literal.shape(), src_index); const int64_t dest_linear_index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), dest_index); const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); char* dest_address = static_cast<char*>(untyped_data()) + dest_linear_index * primitive_size; const char* source_address = static_cast<const char*>(src_literal.untyped_data()) + src_linear_index * primitive_size; if (dest_address != source_address) { memcpy(dest_address, source_address, primitive_size); } } /* static */ absl::StatusOr<Literal> MutableLiteralBase::CreateFromProto( const LiteralProto& proto, bool prohibit_empty_literal) { if (!proto.has_shape()) { return InvalidArgument("LiteralProto has no shape"); } Shape shape(proto.shape()); if (ShapeUtil::HasPrimitiveType(shape, OPAQUE_TYPE)) { return InvalidArgument( "Literal shape cannot include OPAQUE_TYPE sub-shape"); } if (!LayoutUtil::HasLayout(shape)) { return InvalidArgument("LiteralProto has no layout"); } if (LayoutUtil::IsSparseArray(shape)) { return Unimplemented("Sparse literals are not supported"); } TF_RETURN_IF_ERROR(ShapeUtil::ValidateShapeWithOptionalLayout(shape)); Literal literal(shape); TF_RETURN_IF_ERROR(literal.root_piece_.ForEachMutableSubpieceWithStatus( [&](const ShapeIndex& index, Piece* piece) -> absl::Status { const LiteralProto* proto_element = &proto; for (int64_t i : index) { CHECK(i < proto_element->tuple_literals_size()); proto_element = &proto_element->tuple_literals(i); } if (piece->subshape().IsTuple()) { if (proto_element->tuple_literals_size() != ShapeUtil::TupleElementCount(piece->subshape())) { return InvalidArgument( "Expected %d tuple elements in LiteralProto, has %d", ShapeUtil::TupleElementCount(piece->subshape()), proto_element->tuple_literals_size()); } return absl::OkStatus(); } if (piece->subshape().element_type() == TOKEN) { return absl::OkStatus(); } CHECK(piece->subshape().IsArray()); // When prohibit_empty_literal is false (allowing literal with no // values), only copy from proto if the literal proto has values. This // mode is used for a learned cost model. if (prohibit_empty_literal || LiteralProtoHasValues(*proto_element)) { TF_RETURN_IF_ERROR(piece->CopyFromProto(*proto_element)); } return absl::OkStatus(); })); return std::move(literal); } TF_RETURN_IF_ERROR(literal.root_piece_.ForEachMutableSubpieceWithStatus( Literal Literal::SubLiteral(ShapeIndexView shape_index) { if (!shape_index.empty()) { auto decomposed = this->DecomposeTuple(); return decomposed.at(shape_index.front()) .SubLiteral(shape_index.subspan(1)); } else { return std::move(*this); } } std::vector<Literal> Literal::DecomposeTuple() { CHECK(shape().IsTuple()); std::vector<Literal> elements; const auto tuple_element_count = ShapeUtil::TupleElementCount(shape()); elements.reserve(tuple_element_count); for (int i = 0; i < tuple_element_count; ++i) { elements.push_back(Literal(ShapeUtil::GetSubshape(shape(), {i}), /*allocate_arrays=*/false)); Literal& element = elements.back(); element.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* dest_piece) { if (dest_piece->subshape().IsTuple()) { return; } ShapeIndex src_index = {i}; for (int64_t j : index) { src_index.push_back(j); } Piece& src_piece = piece(src_index); // Move the respective buffer over to the element Literal. dest_piece->MoveDataFrom(src_piece); }); } // Set this literal to be nil-shaped. *this = Literal(); return elements; } [&](const ShapeIndex& index, Piece* dest_piece) { if (dest_piece->subshape().IsTuple()) { return; } ShapeIndex src_index = {i}; for (int64_t j : index) { src_index.push_back(j); } Piece& src_piece = piece(src_index); // Move the respective buffer over to the element Literal. dest_piece->MoveDataFrom(src_piece); }); void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } int32_t LiteralBase::Piece::GetDynamicSize(int64_t dim_index) const { CHECK(LayoutUtil::IsDenseArray(subshape())); if (!subshape_->is_dynamic_dimension(dim_index)) { // This is a static dimension, return size. return subshape_->dimensions(dim_index); } return dynamic_size_buffer()[dim_index]; } void LiteralBase::Piece::SetDynamicSize(int64_t dim_index, int32_t size) { CHECK(LayoutUtil::IsDenseArray(subshape())); CHECK(subshape_->is_dynamic_dimension(dim_index)); dynamic_size_buffer()[dim_index] = size; } void LiteralBase::Piece::AllocateBuffers() { const int64_t bytes = total_bytes_dense(); if (bytes > kMaxInlinedBytes) { CHECK_EQ(buffer(), nullptr); rep_.emplace<DenseRep>(); set_buffer( static_cast<char*>(tsl::port::AlignedMalloc(bytes, kMinimumAlignment))); } else { rep_.emplace<DenseInlinedRep>(); } } void LiteralBase::Piece::DeallocateBuffers() { if (auto* array_rep = GetDenseRep()) { tsl::port::AlignedFree(array_rep->data); rep_.emplace<Uninitialized>(); } } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } absl::Status LiteralBase::Piece::CopyFrom(const LiteralBase::Piece& src, bool only_dynamic_bound) { CHECK(subshape_ != nullptr); CHECK(src.subshape_ != nullptr); CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK(LayoutUtil::IsDenseArray(src.subshape())) << __func__ << " is only supported for dense arrays: " << src.subshape(); if (!only_dynamic_bound) { CHECK(ShapeUtil::Compatible(subshape(), src.subshape())); } if (src.array_value_state_ == ArrayValueState::kUnknown || src.array_value_state_ == ArrayValueState::kUndetermined) { if (array_value_state_ == ArrayValueState::kKnown) { DeallocateBuffers(); } array_value_state_ = src.array_value_state_; return absl::OkStatus(); } else { CHECK(src.array_value_state_ == ArrayValueState::kKnown); if (array_value_state_ == ArrayValueState::kUndetermined || array_value_state_ == ArrayValueState::kUnknown) { AllocateBuffers(); } array_value_state_ = src.array_value_state_; } if (ShapeUtil::Equal(subshape(), src.subshape())) { // If the layouts are equal it's faster just to memcpy. memcpy(buffer(), src.buffer(), src.size_bytes_dense()); } else { std::vector<int64_t> origin(subshape().rank(), 0); primitive_util::ArrayTypeSwitch<void>( [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, subshape().element_type()); } DCHECK_EQ(dynamic_size_buffer_bytes(), src.dynamic_size_buffer_bytes()); if (subshape().is_dynamic() && src.subshape().is_dynamic()) { memcpy(dynamic_size_buffer(), src.dynamic_size_buffer(), src.dynamic_size_buffer_bytes()); } return absl::OkStatus(); } [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, void MutableLiteralBase::SetDynamicSize(int64_t dim_index, int32_t size) { return SetDynamicSize(dim_index, {}, size); } void MutableLiteralBase::SetDynamicSize(int64_t dim_index, const ShapeIndex& shape_index, int32_t size) { Shape* subshape = ShapeUtil::GetMutableSubshape(mutable_shape_do_not_use(), shape_index); CHECK(LayoutUtil::IsDenseArray(*subshape)) << __func__ << " is only supported for dense arrays: " << *subshape; CHECK_GE(subshape->dimensions(dim_index), size); subshape->set_dynamic_dimension(dim_index, true); CHECK_EQ(&piece(shape_index).subshape(), subshape); piece(shape_index).SetDynamicSize(dim_index, size); } absl::Status MutableLiteralBase::CopyFrom(const LiteralSlice& src_literal, const ShapeIndex& dest_shape_index, const ShapeIndex& src_shape_index, bool only_dynamic_bound) { const Shape& dest_subshape = ShapeUtil::GetSubshape(shape(), dest_shape_index); const Shape& src_subshape = ShapeUtil::GetSubshape(src_literal.shape(), src_shape_index); if (only_dynamic_bound) { auto& bound_shape = dest_subshape.is_static() ? src_subshape : dest_subshape; auto& compact_shape = dest_subshape.is_static() ? dest_subshape : src_subshape; CHECK(ShapeUtil::DynamicShapeIsCompatible(compact_shape, bound_shape)) << compact_shape.ToString() << " vs " << bound_shape.ToString(); } else { if (!ShapeUtil::Compatible(dest_subshape, src_subshape)) { return InvalidArgument( "Destination subshape incompatible with source subshape: %s vs %s", ShapeUtil::HumanString(dest_subshape), ShapeUtil::HumanString(src_subshape)); } } return mutable_root_piece().ForEachMutableSubpieceWithStatus( [&](const ShapeIndex& index, Piece* piece) { if (!piece->subshape().IsArray()) { return absl::OkStatus(); } // Determine if this index is in the part of this literal that we want // to copy over from src_literal. bool in_subtree_to_copy = true; for (int i = 0; i < dest_shape_index.size(); ++i) { if (index[i] != dest_shape_index[i]) { in_subtree_to_copy = false; break; } } if (!in_subtree_to_copy) { return absl::OkStatus(); } // Construct the index of the corresponding piece in the source literal. ShapeIndex src_piece_index = src_shape_index; for (int64_t i = dest_shape_index.size(), end = index.size(); i < end; ++i) { src_piece_index.push_back(index[i]); } TF_RETURN_IF_ERROR( piece->CopyFrom(src_literal.piece(src_piece_index), /*only_dynamic_bound=*/only_dynamic_bound)); return absl::OkStatus(); }); } [&](const ShapeIndex& index, Piece* piece) { if (!piece->subshape().IsArray()) { return absl::OkStatus(); } // Determine if this index is in the part of this literal that we want // to copy over from src_literal. bool in_subtree_to_copy = true; for (int i = 0; i < dest_shape_index.size(); ++i) { if (index[i] != dest_shape_index[i]) { in_subtree_to_copy = false; break; } } if (!in_subtree_to_copy) { return absl::OkStatus(); } // Construct the index of the corresponding piece in the source literal. ShapeIndex src_piece_index = src_shape_index; for (int64_t i = dest_shape_index.size(), end = index.size(); i < end; ++i) { src_piece_index.push_back(index[i]); } TF_RETURN_IF_ERROR( piece->CopyFrom(src_literal.piece(src_piece_index), /*only_dynamic_bound=*/only_dynamic_bound)); return absl::OkStatus(); }); absl::Status Literal::MoveFrom(Literal&& src_literal, const ShapeIndex& dest_shape_index) { const Shape& dest_subshape = ShapeUtil::GetSubshape(shape(), dest_shape_index); if (!ShapeUtil::Equal(dest_subshape, src_literal.shape())) { return InvalidArgument( "Destination subshape not equal to source shape: %s vs %s", ShapeUtil::HumanString(dest_subshape), ShapeUtil::HumanString(src_literal.shape())); } src_literal.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& src_index, Piece* src_piece) { if (!src_piece->subshape().IsArray()) { return; } ShapeIndex dest_index = dest_shape_index; for (int64_t i : src_index) { dest_index.push_back(i); } Piece& dest_piece = piece(dest_index); dest_piece.DeallocateBuffers(); dest_piece.MoveDataFrom(*src_piece); }); src_literal.shape_ = MaybeOwningShapePtr(&NilShape()); src_literal.root_piece_ = Piece(); src_literal.root_piece_.set_subshape(src_literal.shape_.get()); return absl::OkStatus(); } [&](const ShapeIndex& src_index, Piece* src_piece) { if (!src_piece->subshape().IsArray()) { return; } ShapeIndex dest_index = dest_shape_index; for (int64_t i : src_index) { dest_index.push_back(i); } Piece& dest_piece = piece(dest_index); dest_piece.DeallocateBuffers(); dest_piece.MoveDataFrom(*src_piece); }); absl::Status MutableLiteralBase::CopySliceFrom( const LiteralSlice& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << shape(); TF_RET_CHECK(LayoutUtil::IsDenseArray(src_literal.shape())) << src_literal.shape(); TF_RET_CHECK(ShapeUtil::SameElementType(src_literal.shape(), shape())); TF_RET_CHECK(src_literal.shape().rank() == src_base.size()); TF_RET_CHECK(shape().rank() == dest_base.size()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, void MutableLiteralBase::PopulateR1(const tsl::core::Bitmap& values) { CHECK(shape().IsArray()); CHECK_EQ(shape().rank(), 1); CHECK_EQ(element_count(), values.bits()); CHECK_EQ(shape().element_type(), PRED); for (int64_t i = 0; i < static_cast<int64_t>(values.bits()); ++i) { Set({i}, values.get(i)); } } void MutableLiteralBase::PopulateInplaceInternal( absl::FunctionRef<void(void*, absl::Span<const int64_t>, int)> populator, bool parallel) { const Shape& this_shape = shape(); const int64_t rank = this_shape.rank(); DCHECK(LayoutUtil::IsDenseArray(this_shape)); char* const dest_base = static_cast<char*>(untyped_data()); if (rank > 0) { StrideConfig stride_config(this_shape, this_shape, this_shape.dimensions()); const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); const int64_t num_elements = ShapeUtil::ElementsIn(shape()); // If we are rank-1 and we are `parallel`, it is better to use a smaller // `step` than what `StrideConfig` does: stick the entire dimension in the // inner-most loop. if (parallel && this_shape.rank() == 1) { const int64_t thread_count = ShapeUtil::GetForEachIndexParallelThreadCount(); // Let's just divide up the array into small amounts per thread. stride_config.dest_stride = stride_config.minor_loop_size = num_elements > 32 ? std::max<int64_t>(num_elements / thread_count, 1) : num_elements; stride_config.step = {stride_config.minor_loop_size}; } auto init_function = [&](absl::Span<const int64_t> indexes, int thread_id) -> absl::StatusOr<bool> { const int64_t index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), indexes); DimensionVector minor_scan_indexes(rank, 0); std::copy(indexes.begin(), indexes.end(), minor_scan_indexes.begin()); char* dest_ptr = dest_base + index * primitive_size; char* const dest_end = dest_base + // This handles the case where minor_loop_size does not evenly divide // the most minor dimension. std::min(index + stride_config.minor_loop_size, num_elements) * primitive_size; while (dest_ptr < dest_end) { populator(dest_ptr, minor_scan_indexes, thread_id); ++minor_scan_indexes[stride_config.minor_dimension]; dest_ptr += primitive_size; } return true; }; if (parallel) { ShapeUtil::ForEachIndexParallel(this_shape, stride_config.base, stride_config.dimensions, stride_config.step, init_function); } else { ShapeUtil::ForEachIndex( this_shape, stride_config.base, stride_config.dimensions, stride_config.step, [&init_function]( absl::Span<const int64_t> indexes) -> absl::StatusOr<bool> { auto result_ignored = init_function(indexes, /*thread_id=*/-1); return true; }); } } else { // For scalars. populator(dest_base, {}, /*thread_id=*/-1); } } auto init_function = [&](absl::Span<const int64_t> indexes, int thread_id) -> absl::StatusOr<bool> { const int64_t index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), indexes); DimensionVector minor_scan_indexes(rank, 0); std::copy(indexes.begin(), indexes.end(), minor_scan_indexes.begin()); char* dest_ptr = dest_base + index * primitive_size; char* const dest_end = dest_base + // This handles the case where minor_loop_size does not evenly divide // the most minor dimension. std::min(index + stride_config.minor_loop_size, num_elements) * primitive_size; while (dest_ptr < dest_end) { populator(dest_ptr, minor_scan_indexes, thread_id); ++minor_scan_indexes[stride_config.minor_dimension]; dest_ptr += primitive_size; } return true; }; [&init_function]( absl::Span<const int64_t> indexes) -> absl::StatusOr<bool> { auto result_ignored = init_function(indexes, /*thread_id=*/-1); return true; }); absl::Status MutableLiteralBase::PopulateInplace( absl::FunctionRef<void(void*, absl::Span<const int64_t>)> populator) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); PopulateInplaceInternal( [&](void* dest, absl::Span<const int64_t> indexes, int /*thread_id*/) { return populator(dest, indexes); }, /*parallel=*/false); return absl::OkStatus(); } absl::Status MutableLiteralBase::PopulateInplaceParallel( absl::FunctionRef<void(void*, absl::Span<const int64_t>, int)> populator) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); PopulateInplaceInternal(populator, /*parallel=*/element_count() > 32); return absl::OkStatus(); } Literal LiteralBase::Relayout(const Layout& new_layout, const ShapeIndex& shape_index) const { // Create new shape with 'new_layout' set at the given shape index. Shape new_shape = shape(); Shape* subshape = ShapeUtil::GetMutableSubshape(&new_shape, shape_index); TF_CHECK_OK(LayoutUtil::ValidateLayoutForShape(new_layout, *subshape)); *subshape->mutable_layout() = new_layout; // LINT.IfChange // s4 literals are stored in uint8_t/int8_t, therefore element_size_in_bits // must be removed. if (subshape->layout().element_size_in_bits() == 4) { subshape->mutable_layout()->set_element_size_in_bits(0); } // LINT.ThenChange(//tensorflow/compiler/xla/types.h) Literal result(new_shape); TF_CHECK_OK(result.CopyFrom(*this)); return result; } Literal LiteralBase::Relayout(const Shape& shape_with_layout) const { CHECK(ShapeUtil::Compatible(shape_with_layout, shape())) << "Given shape_with_layout " << ShapeUtil::HumanString(shape_with_layout) << " not compatible with literal shape " << ShapeUtil::HumanString(shape()); Literal result = CreateFromShape(shape_with_layout); ShapeUtil::ForEachSubshape( result.shape(), [this, &result](const Shape& subshape, const ShapeIndex& index) { if (subshape.IsArray()) { TF_CHECK_OK(result.CopyFrom(*this, /*dest_shape_index=*/index, /*src_shape_index=*/index)); } }); return result; } [this, &result](const Shape& subshape, const ShapeIndex& index) { if (subshape.IsArray()) { TF_CHECK_OK(result.CopyFrom(*this, /*dest_shape_index=*/index, /*src_shape_index=*/index)); } }); Literal LiteralBase::ToBoundedDynamic(const Shape& bounded_shape) const { CHECK(bounded_shape.is_dynamic()); Literal result(bounded_shape); ShapeUtil::ForEachSubshape( shape(), [&](const Shape& subshape, const ShapeIndex& index) { if (!subshape.IsArray()) { return; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (bounded_shape.is_dynamic_dimension(i)) { result.SetDynamicSize(i, subshape.dimensions(i)); } } }); TF_CHECK_OK(result.CopyFrom(*this, {}, {}, /*only_dynamic_bound=*/true)); return result; } shape(), [&](const Shape& subshape, const ShapeIndex& index) { if (!subshape.IsArray()) { return; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (bounded_shape.is_dynamic_dimension(i)) { result.SetDynamicSize(i, subshape.dimensions(i)); } } }); Literal LiteralBase::ToStatic() const { // Create new shape with 'new_layout' set at the given shape index. Shape new_shape = shape(); ShapeUtil::ForEachMutableSubshape( &new_shape, [this](Shape* subshape, const ShapeIndex& index) { if (!subshape->IsArray()) { return; } for (int64_t i = 0; i < subshape->rank(); ++i) { // GetDynamicSize has a 32-bit return type and may truncate static // dimensions, so make sure to skip. if (!subshape->is_dynamic_dimension(i)) continue; subshape->set_dynamic_dimension(i, false); subshape->set_dimensions(i, GetDynamicSize(i, index)); } }); Literal result(new_shape); TF_CHECK_OK(result.CopyFrom(*this, {}, {}, /*only_dynamic_bound=*/true)); return result; } &new_shape, [this](Shape* subshape, const ShapeIndex& index) { if (!subshape->IsArray()) { return; } for (int64_t i = 0; i < subshape->rank(); ++i) { // GetDynamicSize has a 32-bit return type and may truncate static // dimensions, so make sure to skip. if (!subshape->is_dynamic_dimension(i)) continue; subshape->set_dynamic_dimension(i, false); subshape->set_dimensions(i, GetDynamicSize(i, index)); } }); absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { absl::StatusOr<Literal> LiteralBase::Broadcast( const Shape& result_shape, absl::Span<const int64_t> dimensions) const { const LiteralBase& src = *this; const Shape& src_shape = shape(); if (!src_shape.IsArray()) { return InvalidArgument("Broadcast only supports arrays."); } const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(src_shape.element_type()); switch (primitive_size) { case 0: return BroadcastHelper<0>(src, src_shape, result_shape, dimensions); case 1: return BroadcastHelper<1>(src, src_shape, result_shape, dimensions); case 2: return BroadcastHelper<2>(src, src_shape, result_shape, dimensions); case 4: return BroadcastHelper<4>(src, src_shape, result_shape, dimensions); case 8: return BroadcastHelper<8>(src, src_shape, result_shape, dimensions); case 16: return BroadcastHelper<16>(src, src_shape, result_shape, dimensions); default: LOG(FATAL) << "Unhandled primitive size " << primitive_size; return InvalidArgument("Unhandled primitive size"); break; } } absl::StatusOr<Literal> LiteralBase::Reshape( absl::Span<const int64_t> dimensions) const { if (!LayoutUtil::IsDenseArray(shape())) { return InvalidArgument("Reshape is only supported for dense arrays."); } if (shape().is_dynamic()) { // TODO(b/243182930): We should consider supporting dynamic reshape. return Unimplemented("Dynamic reshape is not implemented."); } Literal output; if (!LayoutUtil::IsMonotonicWithDim0Major(shape().layout())) { output = Relayout(LayoutUtil::GetDefaultLayoutForRank(shape().rank())); } else { output = Clone(); } // Because the layout is monotonic, we can simply reuse the same sequence of // values without changing their order. *output.mutable_shape_do_not_use() = ShapeUtil::MakeShape(shape().element_type(), dimensions); int64_t elements_before = ShapeUtil::ElementsIn(shape()); int64_t elements_after = ShapeUtil::ElementsIn(output.shape()); if (elements_before != elements_after) { return InvalidArgument( "Shapes before and after Literal::Reshape have different numbers " "of elements: %s vs %s.", ShapeUtil::HumanString(shape()), ShapeUtil::HumanString(output.shape())); } return std::move(output); } Literal LiteralBase::Transpose(absl::Span<const int64_t> permutation) const { CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); CHECK(shape().rank() == permutation.size() && IsPermutation(permutation)) << "Given permutation is not a permutation of dimension numbers"; // To transpose the array, we just permute the dimensions and layout, and // do a straight memory copy of the raw data set. // This is considerably faster than iterating over every array element using // the EachCell<>() and Set<>() APIs. Shape permuted_shape = ShapeUtil::PermuteDimensions(permutation, shape()); // Replace the layout with one affine to this shape, such that a // transpose operation can be performed by leaving the flat values // representation intact. // For example, consider the shape F32[11,8]{1,0} under a {1,0} permutation. // The shape with affine layout resulting from that operation will be // F32[8,11]{0,1}, since it leaves the original most minor (the 8 sized), the // most minor. // // Essentially, given MinMaj(Di) the position of the Di dimension within the // minor to major vector, and given T(Di) the index that the original Di // dimension has within the transposed array, a layout is affine if // MinMaj(Di) == TMinMaj(T(Di)), with TMinMaj() being the minor to major // vector of the affine layout. std::vector<int64_t> inverse_permutation = InversePermutation(permutation); CHECK(LayoutUtil::IsDenseArray(permuted_shape)); Layout* layout = permuted_shape.mutable_layout(); layout->clear_minor_to_major(); for (auto index : LayoutUtil::MinorToMajor(shape())) { layout->add_minor_to_major(inverse_permutation[index]); } Literal new_literal(permuted_shape); if (shape().is_dynamic()) { for (int64_t i = 0; i < shape().rank(); i++) { if (shape().is_dynamic_dimension(i)) { // Set the dynamic size of any dynamic dimension in the transposed // literal. new_literal.SetDynamicSize(inverse_permutation[i], GetDynamicSize(i)); } } } DCHECK_EQ(ShapeUtil::ByteSizeOf(new_literal.shape()), ShapeUtil::ByteSizeOf(shape())); std::memcpy(new_literal.untyped_data(), untyped_data(), size_bytes()); return new_literal; } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( Literal LiteralBase::Slice(absl::Span<const int64_t> start_indices, absl::Span<const int64_t> limit_indices) const { CHECK(shape().IsArray()) << "tuple is not supported for slice"; DimensionVector result_dimensions; for (int64_t dnum = 0; dnum < shape().rank(); ++dnum) { CHECK_GE(start_indices[dnum], 0); CHECK_LE(limit_indices[dnum], shape().dimensions(dnum)) << "dnum = " << dnum; int64_t dimension = limit_indices[dnum] - start_indices[dnum]; CHECK_GE(dimension, 0) << "dnum = " << dnum; result_dimensions.push_back(dimension); } auto result_shape = ShapeUtil::MakeShapeWithDenseLayout( shape().element_type(), result_dimensions, LayoutUtil::MinorToMajor(shape())); ShapeUtil::CopyDynamicDimensions(&result_shape, shape()); Literal result_literal(result_shape); primitive_util::ArrayTypeSwitch<void>( [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; return SliceInternal<NativeT>(*this, start_indices, result_literal); }, result_shape.element_type()); return result_literal; } Literal LiteralBase::Clone() const { Literal result(shape()); TF_CHECK_OK(result.CopyFrom(*this)); return result; } std::unique_ptr<Literal> LiteralBase::CloneToUnique() const { auto result = std::make_unique<Literal>(shape()); TF_CHECK_OK(result->CopyFrom(*this)); return result; } bool LiteralBase::IsDetermined(const ShapeIndex& shape_index) const { return piece(shape_index).IsDetermined(); } bool LiteralBase::IsKnown(const ShapeIndex& shape_index) const { return piece(shape_index).IsKnown(); } std::string LiteralBase::GetAsString(absl::Span<const int64_t> multi_index, const ShapeIndex& shape_index) const { const Shape& subshape = ShapeUtil::GetSubshape(shape(), shape_index); CHECK(LayoutUtil::IsDenseArray(subshape)); return primitive_util::ArrayTypeSwitch<std::string>( [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, subshape.element_type()); } [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, std::optional<int64_t> LiteralBase::GetIntegralAsS64( absl::Span<const int64_t> multi_index) const { CHECK(LayoutUtil::IsDenseArray(shape())); return primitive_util::PrimitiveTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, std::optional<double> LiteralBase::GetAsDouble( absl::Span<const int64_t> multi_index) const { const Shape& s = shape(); CHECK(LayoutUtil::IsDenseArray(s)); return primitive_util::PrimitiveTypeSwitch<std::optional<double>>( [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, s.element_type()); } [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, std::optional<double> LiteralBase::GetSumAsDouble( absl::Span<const int64_t> linear_indices) const { const Shape& s = shape(); CHECK(LayoutUtil::IsDenseArray(s)); if (!primitive_util::IsFloatingPointType(s.element_type())) { return std::nullopt; } return primitive_util::FloatingPointTypeSwitch<double>( [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, s.element_type()); } [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, std::optional<complex128> LiteralBase::GetAsComplex128( absl::Span<const int64_t> multi_index) const { return primitive_util::PrimitiveTypeSwitch<std::optional<complex128>>( [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, absl::Status MutableLiteralBase::SetIntegralAsS64( absl::Span<const int64_t> multi_index, int64_t value) { CHECK(LayoutUtil::IsDenseArray(shape())); return primitive_util::PrimitiveTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, absl::Status MutableLiteralBase::SetFromDouble( absl::Span<const int64_t> multi_index, double value) { CHECK(LayoutUtil::IsDenseArray(shape())); if (!primitive_util::IsFloatingPointType(shape().element_type())) { return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); } primitive_util::FloatingPointTypeSwitch<void>( [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, shape().element_type()); return absl::OkStatus(); } [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, void PrintShape(bool print_layout, const Shape& shape, Printer* printer) { if (print_layout) { ShapeUtil::PrintHumanStringWithLayout(printer, shape); } else { ShapeUtil::PrintHumanString(printer, shape); } } void TuplePrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); printer->Append(oneline ? "( " : "(\n"); for (int i = 0; i < ShapeUtil::TupleElementCount(subshape); ++i) { ShapeIndex element_index = shape_index; element_index.push_back(i); if (i > 0) printer->Append(oneline ? ", " : ",\n"); PrintHelper(literal, element_index, print_shape, print_layout, oneline, printer); } printer->Append(oneline ? " )" : "\n)"); } void DenseArrayPrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); int64_t rank = subshape.rank(); const absl::string_view linebreak = oneline ? " " : "\n"; std::function<void(absl::Span<const int64_t> dimensions, std::vector<int64_t>*)> print_recursive = [&](absl::Span<const int64_t> dimensions, std::vector<int64_t>* accum_indices) { // dimensions.size() decreases by 1 at each recursive call, // and accum_indices->size() increases by 1. // Their sum is equal to the rank of the tensor. CHECK_EQ(rank, dimensions.size() + accum_indices->size()); auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; if (dimensions.empty()) { // Display predicates as 0s and 1s so that the string is more dense. std::string elem; if (subshape.element_type() == PRED && rank > 0) { elem = literal.Get<bool>(*accum_indices, shape_index) ? "1" : "0"; } else { elem = literal.GetAsString(*accum_indices, shape_index); } printer->Append(elem); } else { printer->Append(brace_to_string("{")); for (int i = 0; i < dimensions[0]; ++i) { accum_indices->push_back(i); print_recursive(dimensions.subspan(1), accum_indices); accum_indices->pop_back(); if (i < dimensions[0] - 1) { printer->Append(","); printer->Append(dimensions.size() > 1 ? linebreak : " "); } } printer->Append(brace_to_string("}")); } }; if (print_shape) { PrintShape(print_layout, subshape, printer); if (subshape.is_dynamic()) { printer->Append("("); for (int64_t i = 0; i < subshape.dimensions_size(); ++i) { printer->Append(literal.GetDynamicSize(i, shape_index)); if (i < subshape.dimensions_size() - 1) { printer->Append(","); } } printer->Append(")"); } printer->Append(" "); } std::vector<int64_t> indices = {}; std::vector<int64_t> dimensions; dimensions.reserve(subshape.rank()); for (int64_t i = 0; i < subshape.rank(); ++i) { dimensions.push_back(literal.GetDynamicSize(i, shape_index)); } print_recursive(dimensions, &indices); } print_recursive = [&](absl::Span<const int64_t> dimensions, std::vector<int64_t>* accum_indices) { // dimensions.size() decreases by 1 at each recursive call, // and accum_indices->size() increases by 1. // Their sum is equal to the rank of the tensor. CHECK_EQ(rank, dimensions.size() + accum_indices->size()); auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; if (dimensions.empty()) { // Display predicates as 0s and 1s so that the string is more dense. std::string elem; if (subshape.element_type() == PRED && rank > 0) { elem = literal.Get<bool>(*accum_indices, shape_index) ? "1" : "0"; } else { elem = literal.GetAsString(*accum_indices, shape_index); } printer->Append(elem); } else { printer->Append(brace_to_string("{")); for (int i = 0; i < dimensions[0]; ++i) { accum_indices->push_back(i); print_recursive(dimensions.subspan(1), accum_indices); accum_indices->pop_back(); if (i < dimensions[0] - 1) { printer->Append(","); printer->Append(dimensions.size() > 1 ? linebreak : " "); } } printer->Append(brace_to_string("}")); } }; auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; void PrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); CHECK(LayoutUtil::HasLayout(literal.shape())); CHECK(LayoutUtil::HasLayout(subshape)); if (subshape.IsTuple()) { TuplePrintHelper(literal, shape_index, print_shape, print_layout, oneline, printer); } else if (subshape.IsToken()) { printer->Append("token"); } else { CHECK(LayoutUtil::IsDenseArray(subshape)); if (literal.IsKnown(shape_index)) { DenseArrayPrintHelper(literal, shape_index, print_shape, print_layout, oneline, printer); } else { PrintShape(print_layout, subshape, printer); printer->Append(" "); if (literal.IsDetermined(shape_index)) { printer->Append("unknown"); } else { printer->Append("undetermined"); } } } } void LiteralBase::Print(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/false, /*oneline=*/false, printer); } void LiteralBase::PrintOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/false, /*oneline=*/true, printer); } void LiteralBase::PrintWithoutShape(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/false, /*print_layout=*/false, /*oneline=*/false, printer); } void LiteralBase::PrintWithoutShapeOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/false, /*print_layout=*/false, /*oneline=*/true, printer); } void LiteralBase::PrintWithLayout(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/true, /*oneline=*/false, printer); } void LiteralBase::PrintWithLayoutOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/true, /*oneline=*/true, printer); } std::string LiteralBase::ToString() const { StringPrinter printer; Print(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringOneline() const { StringPrinter printer; PrintOneline(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithoutShape() const { StringPrinter printer; PrintWithoutShape(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithoutShapeOneline() const { StringPrinter printer; PrintWithoutShapeOneline(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithLayout() const { StringPrinter printer; PrintWithLayout(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithLayoutOneline() const { StringPrinter printer; PrintWithLayoutOneline(&printer); return std::move(printer).ToString(); } void LiteralBase::EachCellAsString( absl::FunctionRef<void(absl::Span<const int64_t> indices, const std::string& value)> per_cell) const { if (ShapeUtil::IsZeroElementArray(shape())) { return; } auto indices = IndexUtil::LinearIndexToMultidimensionalIndex( shape(), /*linear_index=*/0); do { per_cell(indices, GetAsString(indices)); } while (IndexUtil::BumpIndices(shape(), absl::MakeSpan(indices))); } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { absl::StatusOr<Literal> ConvertSwitch(const LiteralBase& literal, PrimitiveType primitive_dest_type) { TF_RET_CHECK(LayoutUtil::IsDenseArray(literal.shape())); if (literal.shape().element_type() == primitive_dest_type) { return literal.Clone(); } // Source Array type requirement is ensured by IsDenseArray before. if (!primitive_util::IsArrayType(primitive_dest_type) || !primitive_util::IsArrayType(literal.shape().element_type())) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(literal.shape().element_type()), PrimitiveType_Name(primitive_dest_type)); } // At this point, we know both src & dst are array types, while src is not // complex type, so we can allocate the result literal here to avoid // duplicating it N^2 times in the conversion implementation. Literal result( ShapeUtil::ChangeElementType(literal.shape(), primitive_dest_type)); TF_RETURN_IF_ERROR(primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { return ConvertIfDestTypeMatches<primitive_type_constant>(literal, result); }, literal.shape().element_type())); return result; } absl::StatusOr<Literal> LiteralBase::Convert( PrimitiveType primitive_dest_type) const { return ConvertSwitch(*this, primitive_dest_type); } absl::StatusOr<Literal> LiteralBase::BitcastConvert( const Shape& dest_shape) const { if (ShapeUtil::ByteSizeOf(dest_shape) != ShapeUtil::ByteSizeOf(shape())) { return InvalidArgument( "Can not bitcast-convert from shape %s to a shape of different size %s", shape().ToString(), dest_shape.ToString()); } if (dest_shape.IsTuple() || shape().IsTuple()) { return InvalidArgument( "bitcast-convert is not valid for tuple shapes %s->%s", shape().ToString(), dest_shape.ToString()); } if (shape().is_dynamic() || dest_shape.is_dynamic()) { return InvalidArgument( "bitcast-convert is not valid for dynamic shape %s->%s", shape().ToString(), dest_shape.ToString()); } Literal out(dest_shape); std::memcpy(out.root_piece_.buffer(), root_piece().buffer(), root_piece().size_bytes_dense()); // Perform the reshape on little endian encoding even on big endian machines. if constexpr (!kLittleEndian) { // Swap byte ordering as per the input data type. size_t input_elem_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); TF_RETURN_IF_ERROR(tsl::ByteSwapArray( const_cast<char*>(out.root_piece().buffer()), input_elem_size, out.root_piece().size_bytes_dense() / input_elem_size)); // Swap byte ordering as per the output data type. size_t output_elem_size = ShapeUtil::ByteSizeOfPrimitiveType(dest_shape.element_type()); TF_RETURN_IF_ERROR(tsl::ByteSwapArray( const_cast<char*>(out.root_piece().buffer()), output_elem_size, out.root_piece().size_bytes_dense() / output_elem_size)); } return out; } absl::StatusOr<Literal> LiteralBase::ConvertToShape( const Shape& dest_shape) const { if (!dest_shape.IsTuple()) { return Convert(dest_shape.element_type()); } std::vector<Literal> elements; const auto tuple_element_count = ShapeUtil::TupleElementCount(shape()); elements.reserve(tuple_element_count); for (int i = 0; i < tuple_element_count; ++i) { auto element = LiteralSlice(*this, {i}); TF_ASSIGN_OR_RETURN( auto new_element, element.ConvertToShape(ShapeUtil::GetSubshape(dest_shape, {i}))); elements.push_back(std::move(new_element)); } return MutableLiteralBase::MoveIntoTuple(absl::MakeSpan(elements)); } /* static */ Literal MutableLiteralBase::MoveIntoTuple( absl::Span<Literal> elements) { std::vector<const Shape*> element_shapes; element_shapes.reserve(elements.size()); for (const Literal& element : elements) { element_shapes.push_back(&element.shape()); } Literal literal(ShapeUtil::MakeTupleShapeWithPtrs(element_shapes), /*allocate_arrays=*/false); for (int i = 0, end = elements.size(); i < end; ++i) { TF_CHECK_OK( literal.MoveFrom(std::move(elements[i]), /*dest_shape_index=*/{i})); } return literal; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualDynamicSize( const LiteralBase::Piece& other) const { DCHECK(ShapeUtil::Compatible(subshape(), other.subshape())); if (subshape().is_static()) { return true; } for (int64_t i = 0; i < subshape().rank(); ++i) { if (GetDynamicSize(i) != other.GetDynamicSize(i)) { return false; } } return true; } bool LiteralBase::Piece::EqualElements(const LiteralBase::Piece& other) const { if (subshape().is_static() && ShapeUtil::Equal(subshape(), other.subshape()) && subshape().IsArray()) { CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(size_bytes_dense(), other.size_bytes_dense()); if (primitive_util::IsSubByteNonPredType(subshape().element_type())) { CHECK(!primitive_util::IsFloatingPointType(subshape().element_type())); auto one_array = buffer(); auto two_array = other.buffer(); const int bits_per_element = primitive_util::BitWidth(subshape().element_type()); const uint8_t mask = LsbMask<uint8_t>(bits_per_element); for (int64_t i = 0; i < size_bytes_dense(); ++i) { if ((one_array[i] & mask) != (two_array[i] & mask)) return false; } return true; } return memcmp(buffer(), other.buffer(), size_bytes_dense()) == 0; } std::vector<int64_t> multi_index; return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeSrcT = NativeTypeOf<primitive_type_constant>; return EqualElementsInternal<NativeSrcT>(other, &multi_index); }, subshape().element_type()); } bool LiteralBase::Equal(const LiteralBase& other, bool layout_sensitive) const { // Checking the structure of tuple literals. Checks for dense arrays are // performed below. if (!ShapeUtil::EqualStructure(shape(), other.shape())) { return false; } return root_piece().ForEachSubpieceWithBool([&](const ShapeIndex& index, const Piece& piece) { const Piece& other_piece = other.piece(index); const Shape& subshape = piece.subshape(); const Shape& other_subshape = other_piece.subshape(); if (subshape.element_type() != other_subshape.element_type()) { return false; } if (!piece.subshape().IsArray()) { return true; } if (subshape.rank() != other_subshape.rank()) { return false; } if (layout_sensitive && (subshape.layout() != other_subshape.layout())) { return false; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (piece.GetDynamicSize(i) != other_piece.GetDynamicSize(i)) { return false; } } if (!piece.EqualElements(other_piece)) { return false; } return true; }); } return root_piece().ForEachSubpieceWithBool([&](const ShapeIndex& index, const Piece& piece) { const Piece& other_piece = other.piece(index); const Shape& subshape = piece.subshape(); const Shape& other_subshape = other_piece.subshape(); if (subshape.element_type() != other_subshape.element_type()) { return false; } if (!piece.subshape().IsArray()) { return true; } if (subshape.rank() != other_subshape.rank()) { return false; } if (layout_sensitive && (subshape.layout() != other_subshape.layout())) { return false; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (piece.GetDynamicSize(i) != other_piece.GetDynamicSize(i)) { return false; } } if (!piece.EqualElements(other_piece)) { return false; } return true; }); static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(std::complex<T> a, std::complex<T> b) { return EqualIncludingNan(a.real(), b.real()) && EqualIncludingNan(a.imag(), b.imag()); } static bool EqualIncludingNan(std::complex<T> a, std::complex<T> b) { return EqualIncludingNan(a.real(), b.real()) && EqualIncludingNan(a.imag(), b.imag()); } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } bool Literal::Piece::IsAll(const Literal& scalar) const { CHECK(ShapeUtil::IsScalar(scalar.shape())) << scalar.shape().ToString(); if (!subshape().IsArray()) { return false; } CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(subshape().element_type(), scalar.shape().element_type()); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, subshape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, int64_t Literal::Piece::CountAll(const Literal& scalar) const { CHECK(ShapeUtil::IsScalar(scalar.shape())) << scalar.shape().ToString(); if (!subshape().IsArray()) { return 0; } CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(subshape().element_type(), scalar.shape().element_type()); return primitive_util::ArrayTypeSwitch<int64_t>( [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, subshape().element_type()); } [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { bool LiteralBase::IsAll(const Literal& scalar) const { return root_piece().IsAll(scalar); } bool LiteralBase::IsAll(int8_t value) const { if (!shape().IsArray()) { return false; } PrimitiveType ty = shape().element_type(); if (primitive_util::IsFloatingPointType(ty)) { return IsAllFloatImpl(value, /*round_value=*/false); } if (primitive_util::IsUnsignedIntegralType(ty) && value < 0) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllFloat(float value) const { return IsAllFloatImpl(value, /*round_value=*/true); } bool LiteralBase::IsAllFloatImpl(float value, bool round_value) const { PrimitiveType ty = shape().element_type(); if (!primitive_util::IsFloatingPointType(ty)) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::FloatingPointTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllComplex(complex64 value) const { PrimitiveType ty = shape().element_type(); if (!primitive_util::IsComplexType(ty)) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::ComplexTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllFirst() const { if (!shape().IsArray()) { return false; } // Empty shapes are not all the first element since there is no first element. if (ShapeUtil::IsZeroElementArray(shape())) { return false; } absl::InlinedVector<int64_t, 4> start_indices(/*n=*/shape().rank(), 0); absl::InlinedVector<int64_t, 4> end_indices(/*n=*/shape().rank(), 1); Literal first = Slice(start_indices, end_indices); return IsAll(first.Reshape({}).value()); } bool LiteralBase::IsR1Iota() const { if (!shape().IsArray()) { return false; } CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); if (shape().rank() != 1) { return false; } return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, shape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, std::optional<int64_t> LiteralBase::IsR1StridedIota() const { if (!shape().IsArray() || shape().rank() != 1) { return std::nullopt; } CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); const int64_t elements = ShapeUtil::ElementsIn(shape()); const PrimitiveType type = shape().element_type(); if (elements <= 1 || !primitive_util::IsIntegralType(type)) { return std::nullopt; } return primitive_util::IntegralTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, bool LiteralBase::IsZero(absl::Span<const int64_t> indices) const { CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, shape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void LiteralBase::Piece::set_array_value_state(ArrayValueState state) { array_value_state_ = state; } LiteralBase::ArrayValueState LiteralBase::Piece::get_array_value_state() const { return array_value_state_; } void LiteralBase::Piece::WriteToProto(LiteralProto* proto) const { *proto->mutable_shape() = subshape().ToProto(); switch (subshape().element_type()) { case PRED: CopyToRepeatedField(proto->mutable_preds(), data<bool>()); break; case U2: *proto->mutable_u2s() = std::string( reinterpret_cast<const char*>(data<u2>().data()), size_bytes_dense()); break; case U4: *proto->mutable_u4s() = std::string( reinterpret_cast<const char*>(data<u4>().data()), size_bytes_dense()); break; case U8: proto->set_u8s(static_cast<const unsigned char*>(data<uint8_t>().data()), element_count()); break; case U16: *proto->mutable_u16s() = std::string(reinterpret_cast<const char*>(data<uint16_t>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_u16s()); } break; case U32: CopyToRepeatedField(proto->mutable_u32s(), data<uint32_t>()); break; case U64: CopyToRepeatedField(proto->mutable_u64s(), data<uint64_t>()); break; case S2: *proto->mutable_s2s() = std::string( reinterpret_cast<const char*>(data<s2>().data()), size_bytes_dense()); break; case S4: *proto->mutable_s4s() = std::string( reinterpret_cast<const char*>(data<s4>().data()), size_bytes_dense()); break; case S8: proto->set_s8s(static_cast<const signed char*>(data<int8_t>().data()), element_count()); break; case S16: *proto->mutable_s16s() = std::string(reinterpret_cast<const char*>(data<int16_t>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_s16s()); } break; case S32: CopyToRepeatedField(proto->mutable_s32s(), data<int32_t>()); break; case S64: CopyToRepeatedField(proto->mutable_s64s(), data<int64_t>()); break; case F8E5M2: *proto->mutable_f8e5m2s() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e5m2>().data()), size_bytes_dense()); break; case F8E4M3FN: *proto->mutable_f8e4m3fns() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3fn>().data()), size_bytes_dense()); break; case F8E4M3B11FNUZ: *proto->mutable_f8e4m3b11fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3b11fnuz>().data()), size_bytes_dense()); break; case F8E5M2FNUZ: *proto->mutable_f8e5m2fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e5m2fnuz>().data()), size_bytes_dense()); break; case F8E4M3FNUZ: *proto->mutable_f8e4m3fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3fnuz>().data()), size_bytes_dense()); break; case F16: *proto->mutable_f16s() = std::string(reinterpret_cast<const char*>(data<half>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_f16s()); } break; case BF16: *proto->mutable_bf16s() = std::string(reinterpret_cast<const char*>(data<bfloat16>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_bf16s()); } break; case F32: CopyToRepeatedField(proto->mutable_f32s(), data<float>()); break; case F64: CopyToRepeatedField(proto->mutable_f64s(), data<double>()); break; case C64: for (complex64 value : data<complex64>()) { proto->add_c64s(value.real()); proto->add_c64s(value.imag()); } break; case C128: for (complex128 value : data<complex128>()) { proto->add_c128s(value.real()); proto->add_c128s(value.imag()); } break; case TUPLE: case TOKEN: // Nothing to do but assign the shape which is done above. return; default: // TODO(b/111551621): Support serializing more PrimitiveTypes. LOG(FATAL) << "Unhandled primitive type " << PrimitiveType_Name(subshape().element_type()); } } const void* LiteralBase::Piece::untyped_data() const { DCHECK(LayoutUtil::IsDenseArray(subshape())) << ShapeUtil::HumanString(subshape()); return buffer(); } void* LiteralBase::Piece::untyped_data() { DCHECK(LayoutUtil::IsDenseArray(subshape())) << ShapeUtil::HumanString(subshape()); return buffer(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status LiteralBase::Piece::CopyFromProto(const LiteralProto& proto) { // These conditions should have been checked in // MutableLiteralBase::CreateFromProto. TF_RET_CHECK(proto.has_shape()); Shape shape(proto.shape()); TF_RET_CHECK(LayoutUtil::HasLayout(shape)); TF_RET_CHECK(ShapeUtil::Equal(shape, subshape())); switch (subshape().element_type()) { case PRED: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<bool>(), proto.preds())); break; case S2: { const std::string& s(proto.s2s()); TF_RET_CHECK(data<s2>().size() * sizeof(s2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case S4: { const std::string& s(proto.s4s()); TF_RET_CHECK(data<s4>().size() * sizeof(s4) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case S8: { auto s8_data = data<int8_t>(); TF_RET_CHECK(proto.s8s().size() == s8_data.size()); std::copy(proto.s8s().begin(), proto.s8s().end(), s8_data.begin()); break; } case S16: { const std::string& s(proto.s16s()); TF_RET_CHECK(data<int16_t>().size() * sizeof(int16_t) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case S32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<int32_t>(), proto.s32s())); break; case S64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<int64_t>(), proto.s64s())); break; case U2: { const std::string& s(proto.u2s()); TF_RET_CHECK(data<u2>().size() * sizeof(u2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case U4: { const std::string& s(proto.u4s()); TF_RET_CHECK(data<u4>().size() * sizeof(u4) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case U8: { auto u8_data = data<uint8_t>(); TF_RET_CHECK(proto.u8s().size() == u8_data.size()); std::copy(proto.u8s().begin(), proto.u8s().end(), u8_data.begin()); break; } case U16: { const std::string& s(proto.u16s()); TF_RET_CHECK(data<uint16_t>().size() * sizeof(uint16_t) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case U32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<uint32_t>(), proto.u32s())); break; case U64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<uint64_t>(), proto.u64s())); break; case F8E5M2: { const std::string& s(proto.f8e5m2s()); TF_RET_CHECK(data<tsl::float8_e5m2>().size() * sizeof(tsl::float8_e5m2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3FN: { const std::string& s(proto.f8e4m3fns()); TF_RET_CHECK(data<tsl::float8_e4m3fn>().size() * sizeof(tsl::float8_e4m3fn) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3B11FNUZ: { const std::string& s(proto.f8e4m3b11fnuzs()); TF_RET_CHECK(data<tsl::float8_e4m3b11fnuz>().size() * sizeof(tsl::float8_e4m3b11fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E5M2FNUZ: { const std::string& s(proto.f8e5m2fnuzs()); TF_RET_CHECK(data<tsl::float8_e5m2fnuz>().size() * sizeof(tsl::float8_e5m2fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3FNUZ: { const std::string& s(proto.f8e4m3fnuzs()); TF_RET_CHECK(data<tsl::float8_e4m3fnuz>().size() * sizeof(tsl::float8_e4m3fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F16: { const std::string& s(proto.f16s()); TF_RET_CHECK(data<half>().size() * sizeof(half) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case BF16: { const std::string& s(proto.bf16s()); TF_RET_CHECK(data<bfloat16>().size() * sizeof(bfloat16) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case F32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<float>(), proto.f32s())); break; case F64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<double>(), proto.f64s())); break; case C64: { auto complex_data = data<complex64>(); TF_RET_CHECK(proto.c64s_size() == complex_data.size() * 2); for (int64_t i = 0; i < complex_data.size(); ++i) { complex_data[i] = complex64{proto.c64s(i * 2), proto.c64s(i * 2 + 1)}; } break; } case C128: { auto complex_data = data<complex128>(); const int64_t complex_data_size_doubled = complex_data.size() * 2; TF_RET_CHECK(proto.c128s_size() == complex_data_size_doubled); for (int64_t i = 0, end = complex_data.size(); i < end; ++i) { complex_data[i] = complex128{proto.c128s(i * 2), proto.c128s(i * 2 + 1)}; } break; } case TUPLE: return InvalidArgument("Should not be called on tuple shapes: %s", ShapeUtil::HumanString(subshape())); default: return InvalidArgument("Is called on unsupported shape: %s", ShapeUtil::HumanString(subshape())); } return absl::OkStatus(); } bool LiteralBase::Piece::IsKnown() const { if (array_value_state_ != ArrayValueState::kKnown) { return false; } if (subshape().IsTuple()) { bool are_all_leaf_arrays_known = true; ForEachSubpiece([&are_all_leaf_arrays_known](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_known &= piece.IsKnown(); }); return are_all_leaf_arrays_known; } return true; } ForEachSubpiece([&are_all_leaf_arrays_known](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_known &= piece.IsKnown(); }); bool LiteralBase::Piece::IsDetermined() const { if (array_value_state_ == ArrayValueState::kUndetermined) { return false; } if (subshape().IsTuple()) { bool are_all_leaf_arrays_determined = true; ForEachSubpiece([&are_all_leaf_arrays_determined](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_determined &= piece.IsDetermined(); }); return are_all_leaf_arrays_determined; } return true; } ForEachSubpiece([&are_all_leaf_arrays_determined](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_determined &= piece.IsDetermined(); }); LiteralProto LiteralBase::ToProto() const { LiteralProto proto; root_piece().ForEachSubpiece( [&](const ShapeIndex& index, const Piece& piece) { LiteralProto* proto_piece = &proto; for (int64_t i : index) { while (proto_piece->tuple_literals_size() <= i) { proto_piece->add_tuple_literals(); } proto_piece = proto_piece->mutable_tuple_literals(i); } piece.WriteToProto(proto_piece); }); return proto; } [&](const ShapeIndex& index, const Piece& piece) { LiteralProto* proto_piece = &proto; for (int64_t i : index) { while (proto_piece->tuple_literals_size() <= i) { proto_piece->add_tuple_literals(); } proto_piece = proto_piece->mutable_tuple_literals(i); } piece.WriteToProto(proto_piece); }); const void* LiteralBase::untyped_data(const ShapeIndex& shape_index) const { return piece(shape_index).untyped_data(); } void* MutableLiteralBase::untyped_data(const ShapeIndex& shape_index) { return piece(shape_index).untyped_data(); } int64_t LiteralBase::size_bytes(const ShapeIndex& shape_index) const { return piece(shape_index).size_bytes_dense(); } std::string LiteralBase::GetR1U8AsString() const { CHECK(shape().IsArray()); CHECK_EQ(shape().rank(), 1); CHECK_EQ(shape().element_type(), U8); return std::string(absl::bit_cast<const char*>(data<uint8_t>().data()), ShapeUtil::ElementsIn(shape())); } void MutableBorrowingLiteral::CopyPieceSubtree(const Shape& shape, const Piece* src_piece, Piece* dest_piece) { DCHECK(ShapeUtil::Equal(src_piece->subshape(), dest_piece->subshape())) << "src_piece has shape: " << ShapeUtil::HumanString(src_piece->subshape()) << "dest_piece has shape: " << ShapeUtil::HumanString(dest_piece->subshape()); dest_piece->set_array_value_state(src_piece->get_array_value_state()); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); Piece child_piece; child_piece.set_subshape(&subshape); CopyPieceSubtree(subshape, &src_piece->child(i), &child_piece); dest_piece->emplace_back(std::move(child_piece)); } } else if (shape.IsArray()) { dest_piece->set_buffer(const_cast<char*>(src_piece->buffer())); } } MutableLiteralBase::~MutableLiteralBase() = default; MutableBorrowingLiteral::MutableBorrowingLiteral( const MutableBorrowingLiteral& literal) : MutableLiteralBase() { shape_ = literal.shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.root_piece(), root_piece_); } MutableBorrowingLiteral& MutableBorrowingLiteral::operator=( const MutableBorrowingLiteral& literal) { shape_ = literal.shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.root_piece(), root_piece_); return *this; } MutableBorrowingLiteral::MutableBorrowingLiteral(MutableLiteralBase* literal) : MutableLiteralBase() { shape_ = literal->shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal->root_piece(), root_piece_); } MutableBorrowingLiteral::MutableBorrowingLiteral( MutableBorrowingLiteral literal, const ShapeIndex& view_root) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(literal.piece(view_root).subshape()); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.piece(view_root), root_piece_); } MutableBorrowingLiteral::MutableBorrowingLiteral(const char* src_buf_ptr, const Shape& shape) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(shape); CHECK(LayoutUtil::HasLayout(*shape_)); CHECK(!shape_->IsTuple()); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); root_piece_->set_buffer(const_cast<char*>(src_buf_ptr)); } MutableBorrowingLiteral::MutableBorrowingLiteral(absl::Span<char*> src_buf_ptrs, const Shape& shape) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(shape); if (!shape_->IsTuple()) { CHECK_EQ(src_buf_ptrs.size(), 1); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); root_piece_->set_buffer(const_cast<char*>(src_buf_ptrs[0])); } else { CHECK(!ShapeUtil::IsNestedTuple(*shape_)); CHECK_EQ(src_buf_ptrs.size(), ShapeUtil::TupleElementCount(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); for (int i = 0; i < src_buf_ptrs.size(); ++i) { Piece child_piece; const auto& src_shape = shape_->tuple_shapes(i); CHECK(src_shape.IsArray()); child_piece.set_subshape(&src_shape); child_piece.set_buffer(src_buf_ptrs[i]); root_piece_->emplace_back(std::move(child_piece)); } } } MutableBorrowingLiteral::MutableBorrowingLiteral(ShapeTree<char*> src_buf_ptrs) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(src_buf_ptrs.shape()); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); BuildPieceSubtree(*shape_, root_piece_); root_piece_->ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); } [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); MutableBorrowingLiteral::~MutableBorrowingLiteral() { if (root_piece_ != nullptr) { delete root_piece_; } } LiteralSlice::LiteralSlice(const LiteralBase& literal) : LiteralBase(), root_piece_(&literal.root_piece()) {} LiteralSlice::LiteralSlice(const LiteralBase& literal, const ShapeIndex& view_root) : LiteralBase(), root_piece_(&literal.piece(view_root)) {} BorrowingLiteral::BorrowingLiteral(const char* src_buf_ptr, const Shape& shape) : LiteralBase(), shape_(std::make_unique<Shape>(shape)) { CHECK(shape_->IsArray()); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); root_piece_.set_buffer(const_cast<char*>(src_buf_ptr)); } BorrowingLiteral::BorrowingLiteral(absl::Span<const char* const> src_buf_ptrs, const Shape& shape) : LiteralBase(), shape_(std::make_unique<Shape>(shape)) { CHECK(shape_->IsTuple()); CHECK(!ShapeUtil::IsNestedTuple(*shape_)); CHECK_EQ(src_buf_ptrs.size(), ShapeUtil::TupleElementCount(*shape_)); root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); BuildPieceSubtree(*shape_, &root_piece_); for (int i = 0, end = src_buf_ptrs.size(); i < end; ++i) { const auto& src_shape = shape_->tuple_shapes(i); CHECK(src_shape.IsArray()); root_piece_.child(i).set_buffer(const_cast<char*>(src_buf_ptrs[i])); } } BorrowingLiteral::BorrowingLiteral(ShapeTree<const char*> src_buf_ptrs) : LiteralBase(), shape_(std::make_unique<Shape>(src_buf_ptrs.shape())) { root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); BuildPieceSubtree(*shape_, &root_piece_); root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); } [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); });
#include "xla/literal.h" #include <algorithm> #include <cmath> #include <complex> #include <cstdint> #include <functional> #include <limits> #include <random> #include <string> #include <tuple> #include <utility> #include <vector> #include "absl/base/casts.h" #include "absl/hash/hash.h" #include "absl/random/random.h" #include "absl/status/status.h" #include "absl/strings/match.h" #include "absl/types/span.h" #include "xla/array.h" #include "xla/array2d.h" #include "xla/array3d.h" #include "xla/array4d.h" #include "xla/index_util.h" #include "xla/layout.h" #include "xla/layout_util.h" #include "xla/literal_util.h" #include "xla/primitive_util.h" #include "xla/shape.h" #include "xla/shape_tree.h" #include "xla/shape_util.h" #include "xla/test.h" #include "xla/types.h" #include "xla/util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/errors.h" #include "tsl/platform/logging.h" // IWYU pragma: keep #include "tsl/platform/macros.h" #include "tsl/platform/ml_dtypes.h" #include "tsl/platform/statusor.h" #include "tsl/platform/test_benchmark.h" class LiteralUtilTest : public ::testing::Test { protected: LiteralUtilTest() { Array4D<float> arr4d({ // clang-format off { // i0=0 { // i1=0 {1, 2, 3}, // i2=0 {4, 5, 6}, // i2=1 {7, 8, 9}, // i2=2 }, { // i1=1 {11, 12, 13}, {14, 15, 16}, {17, 18, 19}, }, }, { // i0=1 { // i1=0 {101, 102, 103}, {104, 105, 106}, {107, 108, 109}, }, { // i1=1 {201, 202, 203}, // i2=0 {204, 205, 206}, // i2=1 {207, 208, 209}, // i2=2 }, }, // clang-format on }); layout_r2_dim0major_ = LayoutUtil::MakeLayout({1, 0}); layout_r2_dim0minor_ = LayoutUtil::MakeLayout({0, 1}); layout_r3_dim0major_ = LayoutUtil::MakeLayout({2, 1, 0}); layout_r3_dim0minor_ = LayoutUtil::MakeLayout({0, 1, 2}); layout_r4_dim0major_ = LayoutUtil::MakeLayout({3, 2, 1, 0}); layout_r4_dim0minor_ = LayoutUtil::MakeLayout({0, 1, 2, 3}); literal_r4_2x2x3x3_dim0major_ = LiteralUtil::CreateR4FromArray4DWithLayout<float>(arr4d, layout_r4_dim0major_); literal_r4_2x2x3x3_dim0minor_ = LiteralUtil::CreateR4FromArray4DWithLayout<float>(arr4d, layout_r4_dim0minor_); } Layout layout_r2_dim0major_; Layout layout_r2_dim0minor_; Layout layout_r3_dim0major_; Layout layout_r3_dim0minor_; Layout layout_r4_dim0major_; Layout layout_r4_dim0minor_; Literal literal_r4_2x2x3x3_dim0major_; Literal literal_r4_2x2x3x3_dim0minor_; }; TEST_F(LiteralUtilTest, CopyFromAndToZeroElement) { const Shape empty_r1_shape = ShapeUtil::MakeShape(F32, {0}); const auto const_nine = LiteralUtil::CreateR1<float>({9}); const auto const_empty = Literal::CreateFromShape(empty_r1_shape); { // Source contains dimension with zero elements. const auto empty = Literal::CreateFromShape(empty_r1_shape); auto nine = LiteralUtil::CreateR1<float>({9}); TF_EXPECT_OK(nine.CopySliceFrom(empty, {0}, {0}, {0})); EXPECT_EQ(nine, const_nine); } { // Copy 0 element to destination with zero elements. auto empty = Literal::CreateFromShape(empty_r1_shape); auto nine = LiteralUtil::CreateR1<float>({9}); TF_EXPECT_OK(empty.CopySliceFrom(nine, {0}, {0}, {0})); EXPECT_EQ(empty, const_empty); } }
LiteralUtilTest_CopyFromArrays
xla/literal_test.cc
bool LiteralProtoHasValues(const LiteralProto& proto) { return !proto.s2s().empty() || !proto.s4s().empty() || !proto.s8s().empty() || !proto.s16s().empty() || proto.s32s_size() || proto.s64s_size() || !proto.u2s().empty() || !proto.u4s().empty() || !proto.u8s().empty() || !proto.u16s().empty() || proto.u32s_size() || proto.u64s_size() || !proto.f8e5m2s().empty() || !proto.f8e4m3fns().empty() || !proto.f8e4m3b11fnuzs().empty() || !proto.f8e5m2fnuzs().empty() || !proto.f8e4m3fnuzs().empty() || !proto.f16s().empty() || !proto.bf16s().empty() || proto.f32s_size() || proto.f64s_size() || proto.c64s_size() || proto.c128s_size() || proto.preds_size() || proto.tuple_literals_size(); } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { const Shape& NilShape() { static const Shape* shape = new Shape(TUPLE, {}, {}, {}); return *shape; } const Shape* TryInternShape(const Shape& shape) { if (shape.IsTuple() && shape.tuple_shapes_size() == 0) { return &NilShape(); } if (shape.IsArray() && shape.dimensions_size() == 0 && shape.is_static() && shape.layout().tiles_size() == 0 && shape.layout().memory_space() == 0) { return &ScalarShape(shape.element_type()); } return nullptr; } StrideConfig::StrideConfig(const Shape& source_shape, const Shape& dest_shape, absl::Span<const int64_t> dimensions) : dimensions(dimensions), base(dimensions.size(), 0), step(dimensions.size(), 1) { if (!dimensions.empty()) { // Selects the shape with the largest minor dimension as the one upon // which to run the tight stride loop. if (dimensions[LayoutUtil::Minor(source_shape.layout(), 0)] >= dimensions[LayoutUtil::Minor(dest_shape.layout(), 0)]) { minor_dimension = LayoutUtil::Minor(source_shape.layout(), 0); dest_stride = IndexUtil::GetDimensionStride(dest_shape, minor_dimension); } else { minor_dimension = LayoutUtil::Minor(dest_shape.layout(), 0); source_stride = IndexUtil::GetDimensionStride(source_shape, minor_dimension); } minor_loop_size = dimensions[minor_dimension]; step[minor_dimension] = minor_loop_size; } } LiteralBase::~LiteralBase() = default; const Shape& LiteralBase::shape() const { return root_piece().subshape(); } const char* LiteralBase::Piece::buffer() const { // std::visit is avoided here due to its code size issues. if (auto* r = std::get_if<DenseRep>(&rep_)) { return r->data; } if (auto* r = std::get_if<DenseInlinedRep>(&rep_)) { return r->data; } DCHECK(std::holds_alternative<TupleRep>(rep_) || std::holds_alternative<Uninitialized>(rep_)); return nullptr; } const LiteralBase::Piece& LiteralBase::piece( const ShapeIndex& shape_index) const { const Piece* piece = &root_piece(); for (const auto i : shape_index) { DCHECK_GE(i, 0); DCHECK_LT(i, piece->children_size()); piece = &piece->child(i); } return *piece; } std::ostream& operator<<(std::ostream& out, const Literal& literal) { out << literal.ToString(); return out; } Shape* MutableLiteralBase::mutable_shape_do_not_use() { const Shape* const_shape = shape_.get(); if (!shape_.OwnsPtr()) { shape_ = MaybeOwningShapePtr(std::make_unique<Shape>(*shape_)); } Shape* shape = shape_.get_mutable(); if (shape != const_shape) { std::function<void(const Shape&, Piece*)> set_piece_shapes = [&set_piece_shapes](const Shape& shape, Piece* piece) { piece->set_subshape(&shape); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); set_piece_shapes(subshape, &piece->child(i)); } } }; set_piece_shapes(*shape, &mutable_root_piece()); } return shape; } [&set_piece_shapes](const Shape& shape, Piece* piece) { piece->set_subshape(&shape); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); set_piece_shapes(subshape, &piece->child(i)); } } }; Literal::Literal() : Literal(NilShape()) {} Literal::Literal(const Shape& shape) : Literal(shape, /*allocate_arrays=*/true) {} void Literal::SetShape(const Shape& shape) { Shape shape_storage; const Shape* shape_ptr = &shape; if (LayoutUtil::HasCustomElementSizeInBits(shape)) { shape_storage = shape; shape_storage.mutable_layout()->set_element_size_in_bits(0); shape_ptr = &shape_storage; } if (const Shape* intered_shape_ptr = TryInternShape(*shape_ptr)) { shape_ = intered_shape_ptr; } else { shape_ = std::make_unique<Shape>(*shape_ptr); } } void Literal::SetPiece(const Shape& shape, Piece* piece, bool allocate_arrays, ArrayValueState leaf_array_value_state) { if (shape.IsTuple()) { for (const Shape& subshape : shape.tuple_shapes()) { Piece child_piece; child_piece.set_subshape(&subshape); SetPiece(subshape, &child_piece, allocate_arrays, leaf_array_value_state); piece->emplace_back(std::move(child_piece)); } } else if (shape.IsArray()) { DCHECK(LayoutUtil::IsDenseArray(shape)) << "literal array storage is currently only supported for dense " "arrays: " << shape; piece->set_array_value_state(leaf_array_value_state); if (leaf_array_value_state == LiteralBase::ArrayValueState::kKnown && allocate_arrays) { piece->AllocateBuffers(); } } } Literal::Literal(const Shape& shape, bool allocate_arrays, ArrayValueState leaf_array_value_state) : MutableLiteralBase() { SetShape(shape); CHECK(leaf_array_value_state != ArrayValueState::kKnown || LayoutUtil::HasLayout(*shape_)); root_piece_.set_subshape(shape_.get()); CHECK(&root_piece_.subshape() == shape_.get()); SetPiece(*shape_, &root_piece_, allocate_arrays, leaf_array_value_state); } Literal::~Literal() { DeallocateBuffers(); } void Literal::DeallocateBuffers() { root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { piece->DeallocateBuffers(); }); } Literal::Literal(Literal&& other) : MutableLiteralBase() { *this = std::move(other); } Literal& Literal::operator=(Literal&& other) { DCHECK(&other.root_piece_.subshape() == other.shape_.get()); using std::swap; swap(shape_, other.shape_); swap(root_piece_, other.root_piece_); DCHECK(&root_piece_.subshape() == shape_.get()); return *this; } Literal LiteralBase::CreateFromShape(const Shape& shape) { Literal literal(shape); literal.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (piece->subshape().IsArray()) { memset(piece->untyped_data(), 0, piece->size_bytes_dense()); } }); return literal; } [&](const ShapeIndex& index, Piece* piece) { if (piece->subshape().IsArray()) { memset(piece->untyped_data(), 0, piece->size_bytes_dense()); } }); Literal LiteralBase::CreateFromShapeWithUnknownLeafArrays(const Shape& shape) { Literal literal(shape, /*allocate_arrays=*/false, ArrayValueState::kUnknown); return literal; } Literal LiteralBase::CreateFromShapeWithUndeterminedLeafArrays( const Shape& shape) { Literal literal(shape, /*allocate_arrays=*/false, ArrayValueState::kUndetermined); return literal; } int32_t LiteralBase::GetDynamicSize(int64_t dim_index) const { return GetDynamicSize(dim_index, {}); } int32_t LiteralBase::GetDynamicSize(int64_t dim_index, const ShapeIndex& shape_index) const { return piece(shape_index).GetDynamicSize(dim_index); } std::optional<int64_t> LiteralBase::GetFirstInteger() const { if (!primitive_util::IsIntegralType(shape().element_type())) { return std::nullopt; } return primitive_util::IntegralTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, void LiteralBase::BuildPieceSubtree(const Shape& shape, Piece* piece) { CHECK(shape.IsTuple()); for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); Piece child_piece; child_piece.set_subshape(&subshape); if (subshape.IsTuple()) { BuildPieceSubtree(subshape, &child_piece); } piece->emplace_back(std::move(child_piece)); } } absl::Status LiteralBase::SerializeToString(std::string* output) const { ShapeProto shape_proto = shape().ToProto(); TF_ASSIGN_OR_RETURN(int64_t size, ShapeUtil::SerializedSizeWithProto(shape(), shape_proto)); output->resize(size); return SerializeWithShapeProto(shape_proto, output->data()); } absl::StatusOr<std::string> LiteralBase::SerializeAsString() const { std::string result; TF_RETURN_IF_ERROR(SerializeToString(&result)); return std::move(result); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { void MutableLiteralBase::CopyElementFrom(const LiteralSlice& src_literal, absl::Span<const int64_t> src_index, absl::Span<const int64_t> dest_index) { DCHECK(LayoutUtil::IsDenseArray(shape())); DCHECK_EQ(shape().element_type(), src_literal.shape().element_type()); const int64_t src_linear_index = IndexUtil::MultidimensionalIndexToLinearIndex(src_literal.shape(), src_index); const int64_t dest_linear_index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), dest_index); const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); char* dest_address = static_cast<char*>(untyped_data()) + dest_linear_index * primitive_size; const char* source_address = static_cast<const char*>(src_literal.untyped_data()) + src_linear_index * primitive_size; if (dest_address != source_address) { memcpy(dest_address, source_address, primitive_size); } } /* static */ absl::StatusOr<Literal> MutableLiteralBase::CreateFromProto( const LiteralProto& proto, bool prohibit_empty_literal) { if (!proto.has_shape()) { return InvalidArgument("LiteralProto has no shape"); } Shape shape(proto.shape()); if (ShapeUtil::HasPrimitiveType(shape, OPAQUE_TYPE)) { return InvalidArgument( "Literal shape cannot include OPAQUE_TYPE sub-shape"); } if (!LayoutUtil::HasLayout(shape)) { return InvalidArgument("LiteralProto has no layout"); } if (LayoutUtil::IsSparseArray(shape)) { return Unimplemented("Sparse literals are not supported"); } TF_RETURN_IF_ERROR(ShapeUtil::ValidateShapeWithOptionalLayout(shape)); Literal literal(shape); TF_RETURN_IF_ERROR(literal.root_piece_.ForEachMutableSubpieceWithStatus( [&](const ShapeIndex& index, Piece* piece) -> absl::Status { const LiteralProto* proto_element = &proto; for (int64_t i : index) { CHECK(i < proto_element->tuple_literals_size()); proto_element = &proto_element->tuple_literals(i); } if (piece->subshape().IsTuple()) { if (proto_element->tuple_literals_size() != ShapeUtil::TupleElementCount(piece->subshape())) { return InvalidArgument( "Expected %d tuple elements in LiteralProto, has %d", ShapeUtil::TupleElementCount(piece->subshape()), proto_element->tuple_literals_size()); } return absl::OkStatus(); } if (piece->subshape().element_type() == TOKEN) { return absl::OkStatus(); } CHECK(piece->subshape().IsArray()); // When prohibit_empty_literal is false (allowing literal with no // values), only copy from proto if the literal proto has values. This // mode is used for a learned cost model. if (prohibit_empty_literal || LiteralProtoHasValues(*proto_element)) { TF_RETURN_IF_ERROR(piece->CopyFromProto(*proto_element)); } return absl::OkStatus(); })); return std::move(literal); } TF_RETURN_IF_ERROR(literal.root_piece_.ForEachMutableSubpieceWithStatus( Literal Literal::SubLiteral(ShapeIndexView shape_index) { if (!shape_index.empty()) { auto decomposed = this->DecomposeTuple(); return decomposed.at(shape_index.front()) .SubLiteral(shape_index.subspan(1)); } else { return std::move(*this); } } std::vector<Literal> Literal::DecomposeTuple() { CHECK(shape().IsTuple()); std::vector<Literal> elements; const auto tuple_element_count = ShapeUtil::TupleElementCount(shape()); elements.reserve(tuple_element_count); for (int i = 0; i < tuple_element_count; ++i) { elements.push_back(Literal(ShapeUtil::GetSubshape(shape(), {i}), /*allocate_arrays=*/false)); Literal& element = elements.back(); element.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* dest_piece) { if (dest_piece->subshape().IsTuple()) { return; } ShapeIndex src_index = {i}; for (int64_t j : index) { src_index.push_back(j); } Piece& src_piece = piece(src_index); // Move the respective buffer over to the element Literal. dest_piece->MoveDataFrom(src_piece); }); } // Set this literal to be nil-shaped. *this = Literal(); return elements; } [&](const ShapeIndex& index, Piece* dest_piece) { if (dest_piece->subshape().IsTuple()) { return; } ShapeIndex src_index = {i}; for (int64_t j : index) { src_index.push_back(j); } Piece& src_piece = piece(src_index); // Move the respective buffer over to the element Literal. dest_piece->MoveDataFrom(src_piece); }); void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } int32_t LiteralBase::Piece::GetDynamicSize(int64_t dim_index) const { CHECK(LayoutUtil::IsDenseArray(subshape())); if (!subshape_->is_dynamic_dimension(dim_index)) { // This is a static dimension, return size. return subshape_->dimensions(dim_index); } return dynamic_size_buffer()[dim_index]; } void LiteralBase::Piece::SetDynamicSize(int64_t dim_index, int32_t size) { CHECK(LayoutUtil::IsDenseArray(subshape())); CHECK(subshape_->is_dynamic_dimension(dim_index)); dynamic_size_buffer()[dim_index] = size; } void LiteralBase::Piece::AllocateBuffers() { const int64_t bytes = total_bytes_dense(); if (bytes > kMaxInlinedBytes) { CHECK_EQ(buffer(), nullptr); rep_.emplace<DenseRep>(); set_buffer( static_cast<char*>(tsl::port::AlignedMalloc(bytes, kMinimumAlignment))); } else { rep_.emplace<DenseInlinedRep>(); } } void LiteralBase::Piece::DeallocateBuffers() { if (auto* array_rep = GetDenseRep()) { tsl::port::AlignedFree(array_rep->data); rep_.emplace<Uninitialized>(); } } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } absl::Status LiteralBase::Piece::CopyFrom(const LiteralBase::Piece& src, bool only_dynamic_bound) { CHECK(subshape_ != nullptr); CHECK(src.subshape_ != nullptr); CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK(LayoutUtil::IsDenseArray(src.subshape())) << __func__ << " is only supported for dense arrays: " << src.subshape(); if (!only_dynamic_bound) { CHECK(ShapeUtil::Compatible(subshape(), src.subshape())); } if (src.array_value_state_ == ArrayValueState::kUnknown || src.array_value_state_ == ArrayValueState::kUndetermined) { if (array_value_state_ == ArrayValueState::kKnown) { DeallocateBuffers(); } array_value_state_ = src.array_value_state_; return absl::OkStatus(); } else { CHECK(src.array_value_state_ == ArrayValueState::kKnown); if (array_value_state_ == ArrayValueState::kUndetermined || array_value_state_ == ArrayValueState::kUnknown) { AllocateBuffers(); } array_value_state_ = src.array_value_state_; } if (ShapeUtil::Equal(subshape(), src.subshape())) { // If the layouts are equal it's faster just to memcpy. memcpy(buffer(), src.buffer(), src.size_bytes_dense()); } else { std::vector<int64_t> origin(subshape().rank(), 0); primitive_util::ArrayTypeSwitch<void>( [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, subshape().element_type()); } DCHECK_EQ(dynamic_size_buffer_bytes(), src.dynamic_size_buffer_bytes()); if (subshape().is_dynamic() && src.subshape().is_dynamic()) { memcpy(dynamic_size_buffer(), src.dynamic_size_buffer(), src.dynamic_size_buffer_bytes()); } return absl::OkStatus(); } [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, void MutableLiteralBase::SetDynamicSize(int64_t dim_index, int32_t size) { return SetDynamicSize(dim_index, {}, size); } void MutableLiteralBase::SetDynamicSize(int64_t dim_index, const ShapeIndex& shape_index, int32_t size) { Shape* subshape = ShapeUtil::GetMutableSubshape(mutable_shape_do_not_use(), shape_index); CHECK(LayoutUtil::IsDenseArray(*subshape)) << __func__ << " is only supported for dense arrays: " << *subshape; CHECK_GE(subshape->dimensions(dim_index), size); subshape->set_dynamic_dimension(dim_index, true); CHECK_EQ(&piece(shape_index).subshape(), subshape); piece(shape_index).SetDynamicSize(dim_index, size); } absl::Status MutableLiteralBase::CopyFrom(const LiteralSlice& src_literal, const ShapeIndex& dest_shape_index, const ShapeIndex& src_shape_index, bool only_dynamic_bound) { const Shape& dest_subshape = ShapeUtil::GetSubshape(shape(), dest_shape_index); const Shape& src_subshape = ShapeUtil::GetSubshape(src_literal.shape(), src_shape_index); if (only_dynamic_bound) { auto& bound_shape = dest_subshape.is_static() ? src_subshape : dest_subshape; auto& compact_shape = dest_subshape.is_static() ? dest_subshape : src_subshape; CHECK(ShapeUtil::DynamicShapeIsCompatible(compact_shape, bound_shape)) << compact_shape.ToString() << " vs " << bound_shape.ToString(); } else { if (!ShapeUtil::Compatible(dest_subshape, src_subshape)) { return InvalidArgument( "Destination subshape incompatible with source subshape: %s vs %s", ShapeUtil::HumanString(dest_subshape), ShapeUtil::HumanString(src_subshape)); } } return mutable_root_piece().ForEachMutableSubpieceWithStatus( [&](const ShapeIndex& index, Piece* piece) { if (!piece->subshape().IsArray()) { return absl::OkStatus(); } // Determine if this index is in the part of this literal that we want // to copy over from src_literal. bool in_subtree_to_copy = true; for (int i = 0; i < dest_shape_index.size(); ++i) { if (index[i] != dest_shape_index[i]) { in_subtree_to_copy = false; break; } } if (!in_subtree_to_copy) { return absl::OkStatus(); } // Construct the index of the corresponding piece in the source literal. ShapeIndex src_piece_index = src_shape_index; for (int64_t i = dest_shape_index.size(), end = index.size(); i < end; ++i) { src_piece_index.push_back(index[i]); } TF_RETURN_IF_ERROR( piece->CopyFrom(src_literal.piece(src_piece_index), /*only_dynamic_bound=*/only_dynamic_bound)); return absl::OkStatus(); }); } [&](const ShapeIndex& index, Piece* piece) { if (!piece->subshape().IsArray()) { return absl::OkStatus(); } // Determine if this index is in the part of this literal that we want // to copy over from src_literal. bool in_subtree_to_copy = true; for (int i = 0; i < dest_shape_index.size(); ++i) { if (index[i] != dest_shape_index[i]) { in_subtree_to_copy = false; break; } } if (!in_subtree_to_copy) { return absl::OkStatus(); } // Construct the index of the corresponding piece in the source literal. ShapeIndex src_piece_index = src_shape_index; for (int64_t i = dest_shape_index.size(), end = index.size(); i < end; ++i) { src_piece_index.push_back(index[i]); } TF_RETURN_IF_ERROR( piece->CopyFrom(src_literal.piece(src_piece_index), /*only_dynamic_bound=*/only_dynamic_bound)); return absl::OkStatus(); }); absl::Status Literal::MoveFrom(Literal&& src_literal, const ShapeIndex& dest_shape_index) { const Shape& dest_subshape = ShapeUtil::GetSubshape(shape(), dest_shape_index); if (!ShapeUtil::Equal(dest_subshape, src_literal.shape())) { return InvalidArgument( "Destination subshape not equal to source shape: %s vs %s", ShapeUtil::HumanString(dest_subshape), ShapeUtil::HumanString(src_literal.shape())); } src_literal.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& src_index, Piece* src_piece) { if (!src_piece->subshape().IsArray()) { return; } ShapeIndex dest_index = dest_shape_index; for (int64_t i : src_index) { dest_index.push_back(i); } Piece& dest_piece = piece(dest_index); dest_piece.DeallocateBuffers(); dest_piece.MoveDataFrom(*src_piece); }); src_literal.shape_ = MaybeOwningShapePtr(&NilShape()); src_literal.root_piece_ = Piece(); src_literal.root_piece_.set_subshape(src_literal.shape_.get()); return absl::OkStatus(); } [&](const ShapeIndex& src_index, Piece* src_piece) { if (!src_piece->subshape().IsArray()) { return; } ShapeIndex dest_index = dest_shape_index; for (int64_t i : src_index) { dest_index.push_back(i); } Piece& dest_piece = piece(dest_index); dest_piece.DeallocateBuffers(); dest_piece.MoveDataFrom(*src_piece); }); absl::Status MutableLiteralBase::CopySliceFrom( const LiteralSlice& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << shape(); TF_RET_CHECK(LayoutUtil::IsDenseArray(src_literal.shape())) << src_literal.shape(); TF_RET_CHECK(ShapeUtil::SameElementType(src_literal.shape(), shape())); TF_RET_CHECK(src_literal.shape().rank() == src_base.size()); TF_RET_CHECK(shape().rank() == dest_base.size()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, void MutableLiteralBase::PopulateR1(const tsl::core::Bitmap& values) { CHECK(shape().IsArray()); CHECK_EQ(shape().rank(), 1); CHECK_EQ(element_count(), values.bits()); CHECK_EQ(shape().element_type(), PRED); for (int64_t i = 0; i < static_cast<int64_t>(values.bits()); ++i) { Set({i}, values.get(i)); } } void MutableLiteralBase::PopulateInplaceInternal( absl::FunctionRef<void(void*, absl::Span<const int64_t>, int)> populator, bool parallel) { const Shape& this_shape = shape(); const int64_t rank = this_shape.rank(); DCHECK(LayoutUtil::IsDenseArray(this_shape)); char* const dest_base = static_cast<char*>(untyped_data()); if (rank > 0) { StrideConfig stride_config(this_shape, this_shape, this_shape.dimensions()); const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); const int64_t num_elements = ShapeUtil::ElementsIn(shape()); // If we are rank-1 and we are `parallel`, it is better to use a smaller // `step` than what `StrideConfig` does: stick the entire dimension in the // inner-most loop. if (parallel && this_shape.rank() == 1) { const int64_t thread_count = ShapeUtil::GetForEachIndexParallelThreadCount(); // Let's just divide up the array into small amounts per thread. stride_config.dest_stride = stride_config.minor_loop_size = num_elements > 32 ? std::max<int64_t>(num_elements / thread_count, 1) : num_elements; stride_config.step = {stride_config.minor_loop_size}; } auto init_function = [&](absl::Span<const int64_t> indexes, int thread_id) -> absl::StatusOr<bool> { const int64_t index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), indexes); DimensionVector minor_scan_indexes(rank, 0); std::copy(indexes.begin(), indexes.end(), minor_scan_indexes.begin()); char* dest_ptr = dest_base + index * primitive_size; char* const dest_end = dest_base + // This handles the case where minor_loop_size does not evenly divide // the most minor dimension. std::min(index + stride_config.minor_loop_size, num_elements) * primitive_size; while (dest_ptr < dest_end) { populator(dest_ptr, minor_scan_indexes, thread_id); ++minor_scan_indexes[stride_config.minor_dimension]; dest_ptr += primitive_size; } return true; }; if (parallel) { ShapeUtil::ForEachIndexParallel(this_shape, stride_config.base, stride_config.dimensions, stride_config.step, init_function); } else { ShapeUtil::ForEachIndex( this_shape, stride_config.base, stride_config.dimensions, stride_config.step, [&init_function]( absl::Span<const int64_t> indexes) -> absl::StatusOr<bool> { auto result_ignored = init_function(indexes, /*thread_id=*/-1); return true; }); } } else { // For scalars. populator(dest_base, {}, /*thread_id=*/-1); } } auto init_function = [&](absl::Span<const int64_t> indexes, int thread_id) -> absl::StatusOr<bool> { const int64_t index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), indexes); DimensionVector minor_scan_indexes(rank, 0); std::copy(indexes.begin(), indexes.end(), minor_scan_indexes.begin()); char* dest_ptr = dest_base + index * primitive_size; char* const dest_end = dest_base + // This handles the case where minor_loop_size does not evenly divide // the most minor dimension. std::min(index + stride_config.minor_loop_size, num_elements) * primitive_size; while (dest_ptr < dest_end) { populator(dest_ptr, minor_scan_indexes, thread_id); ++minor_scan_indexes[stride_config.minor_dimension]; dest_ptr += primitive_size; } return true; }; [&init_function]( absl::Span<const int64_t> indexes) -> absl::StatusOr<bool> { auto result_ignored = init_function(indexes, /*thread_id=*/-1); return true; }); absl::Status MutableLiteralBase::PopulateInplace( absl::FunctionRef<void(void*, absl::Span<const int64_t>)> populator) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); PopulateInplaceInternal( [&](void* dest, absl::Span<const int64_t> indexes, int /*thread_id*/) { return populator(dest, indexes); }, /*parallel=*/false); return absl::OkStatus(); } absl::Status MutableLiteralBase::PopulateInplaceParallel( absl::FunctionRef<void(void*, absl::Span<const int64_t>, int)> populator) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); PopulateInplaceInternal(populator, /*parallel=*/element_count() > 32); return absl::OkStatus(); } Literal LiteralBase::Relayout(const Layout& new_layout, const ShapeIndex& shape_index) const { // Create new shape with 'new_layout' set at the given shape index. Shape new_shape = shape(); Shape* subshape = ShapeUtil::GetMutableSubshape(&new_shape, shape_index); TF_CHECK_OK(LayoutUtil::ValidateLayoutForShape(new_layout, *subshape)); *subshape->mutable_layout() = new_layout; // LINT.IfChange // s4 literals are stored in uint8_t/int8_t, therefore element_size_in_bits // must be removed. if (subshape->layout().element_size_in_bits() == 4) { subshape->mutable_layout()->set_element_size_in_bits(0); } // LINT.ThenChange(//tensorflow/compiler/xla/types.h) Literal result(new_shape); TF_CHECK_OK(result.CopyFrom(*this)); return result; } Literal LiteralBase::Relayout(const Shape& shape_with_layout) const { CHECK(ShapeUtil::Compatible(shape_with_layout, shape())) << "Given shape_with_layout " << ShapeUtil::HumanString(shape_with_layout) << " not compatible with literal shape " << ShapeUtil::HumanString(shape()); Literal result = CreateFromShape(shape_with_layout); ShapeUtil::ForEachSubshape( result.shape(), [this, &result](const Shape& subshape, const ShapeIndex& index) { if (subshape.IsArray()) { TF_CHECK_OK(result.CopyFrom(*this, /*dest_shape_index=*/index, /*src_shape_index=*/index)); } }); return result; } [this, &result](const Shape& subshape, const ShapeIndex& index) { if (subshape.IsArray()) { TF_CHECK_OK(result.CopyFrom(*this, /*dest_shape_index=*/index, /*src_shape_index=*/index)); } }); Literal LiteralBase::ToBoundedDynamic(const Shape& bounded_shape) const { CHECK(bounded_shape.is_dynamic()); Literal result(bounded_shape); ShapeUtil::ForEachSubshape( shape(), [&](const Shape& subshape, const ShapeIndex& index) { if (!subshape.IsArray()) { return; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (bounded_shape.is_dynamic_dimension(i)) { result.SetDynamicSize(i, subshape.dimensions(i)); } } }); TF_CHECK_OK(result.CopyFrom(*this, {}, {}, /*only_dynamic_bound=*/true)); return result; } shape(), [&](const Shape& subshape, const ShapeIndex& index) { if (!subshape.IsArray()) { return; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (bounded_shape.is_dynamic_dimension(i)) { result.SetDynamicSize(i, subshape.dimensions(i)); } } }); Literal LiteralBase::ToStatic() const { // Create new shape with 'new_layout' set at the given shape index. Shape new_shape = shape(); ShapeUtil::ForEachMutableSubshape( &new_shape, [this](Shape* subshape, const ShapeIndex& index) { if (!subshape->IsArray()) { return; } for (int64_t i = 0; i < subshape->rank(); ++i) { // GetDynamicSize has a 32-bit return type and may truncate static // dimensions, so make sure to skip. if (!subshape->is_dynamic_dimension(i)) continue; subshape->set_dynamic_dimension(i, false); subshape->set_dimensions(i, GetDynamicSize(i, index)); } }); Literal result(new_shape); TF_CHECK_OK(result.CopyFrom(*this, {}, {}, /*only_dynamic_bound=*/true)); return result; } &new_shape, [this](Shape* subshape, const ShapeIndex& index) { if (!subshape->IsArray()) { return; } for (int64_t i = 0; i < subshape->rank(); ++i) { // GetDynamicSize has a 32-bit return type and may truncate static // dimensions, so make sure to skip. if (!subshape->is_dynamic_dimension(i)) continue; subshape->set_dynamic_dimension(i, false); subshape->set_dimensions(i, GetDynamicSize(i, index)); } }); absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { absl::StatusOr<Literal> LiteralBase::Broadcast( const Shape& result_shape, absl::Span<const int64_t> dimensions) const { const LiteralBase& src = *this; const Shape& src_shape = shape(); if (!src_shape.IsArray()) { return InvalidArgument("Broadcast only supports arrays."); } const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(src_shape.element_type()); switch (primitive_size) { case 0: return BroadcastHelper<0>(src, src_shape, result_shape, dimensions); case 1: return BroadcastHelper<1>(src, src_shape, result_shape, dimensions); case 2: return BroadcastHelper<2>(src, src_shape, result_shape, dimensions); case 4: return BroadcastHelper<4>(src, src_shape, result_shape, dimensions); case 8: return BroadcastHelper<8>(src, src_shape, result_shape, dimensions); case 16: return BroadcastHelper<16>(src, src_shape, result_shape, dimensions); default: LOG(FATAL) << "Unhandled primitive size " << primitive_size; return InvalidArgument("Unhandled primitive size"); break; } } absl::StatusOr<Literal> LiteralBase::Reshape( absl::Span<const int64_t> dimensions) const { if (!LayoutUtil::IsDenseArray(shape())) { return InvalidArgument("Reshape is only supported for dense arrays."); } if (shape().is_dynamic()) { // TODO(b/243182930): We should consider supporting dynamic reshape. return Unimplemented("Dynamic reshape is not implemented."); } Literal output; if (!LayoutUtil::IsMonotonicWithDim0Major(shape().layout())) { output = Relayout(LayoutUtil::GetDefaultLayoutForRank(shape().rank())); } else { output = Clone(); } // Because the layout is monotonic, we can simply reuse the same sequence of // values without changing their order. *output.mutable_shape_do_not_use() = ShapeUtil::MakeShape(shape().element_type(), dimensions); int64_t elements_before = ShapeUtil::ElementsIn(shape()); int64_t elements_after = ShapeUtil::ElementsIn(output.shape()); if (elements_before != elements_after) { return InvalidArgument( "Shapes before and after Literal::Reshape have different numbers " "of elements: %s vs %s.", ShapeUtil::HumanString(shape()), ShapeUtil::HumanString(output.shape())); } return std::move(output); } Literal LiteralBase::Transpose(absl::Span<const int64_t> permutation) const { CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); CHECK(shape().rank() == permutation.size() && IsPermutation(permutation)) << "Given permutation is not a permutation of dimension numbers"; // To transpose the array, we just permute the dimensions and layout, and // do a straight memory copy of the raw data set. // This is considerably faster than iterating over every array element using // the EachCell<>() and Set<>() APIs. Shape permuted_shape = ShapeUtil::PermuteDimensions(permutation, shape()); // Replace the layout with one affine to this shape, such that a // transpose operation can be performed by leaving the flat values // representation intact. // For example, consider the shape F32[11,8]{1,0} under a {1,0} permutation. // The shape with affine layout resulting from that operation will be // F32[8,11]{0,1}, since it leaves the original most minor (the 8 sized), the // most minor. // // Essentially, given MinMaj(Di) the position of the Di dimension within the // minor to major vector, and given T(Di) the index that the original Di // dimension has within the transposed array, a layout is affine if // MinMaj(Di) == TMinMaj(T(Di)), with TMinMaj() being the minor to major // vector of the affine layout. std::vector<int64_t> inverse_permutation = InversePermutation(permutation); CHECK(LayoutUtil::IsDenseArray(permuted_shape)); Layout* layout = permuted_shape.mutable_layout(); layout->clear_minor_to_major(); for (auto index : LayoutUtil::MinorToMajor(shape())) { layout->add_minor_to_major(inverse_permutation[index]); } Literal new_literal(permuted_shape); if (shape().is_dynamic()) { for (int64_t i = 0; i < shape().rank(); i++) { if (shape().is_dynamic_dimension(i)) { // Set the dynamic size of any dynamic dimension in the transposed // literal. new_literal.SetDynamicSize(inverse_permutation[i], GetDynamicSize(i)); } } } DCHECK_EQ(ShapeUtil::ByteSizeOf(new_literal.shape()), ShapeUtil::ByteSizeOf(shape())); std::memcpy(new_literal.untyped_data(), untyped_data(), size_bytes()); return new_literal; } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( Literal LiteralBase::Slice(absl::Span<const int64_t> start_indices, absl::Span<const int64_t> limit_indices) const { CHECK(shape().IsArray()) << "tuple is not supported for slice"; DimensionVector result_dimensions; for (int64_t dnum = 0; dnum < shape().rank(); ++dnum) { CHECK_GE(start_indices[dnum], 0); CHECK_LE(limit_indices[dnum], shape().dimensions(dnum)) << "dnum = " << dnum; int64_t dimension = limit_indices[dnum] - start_indices[dnum]; CHECK_GE(dimension, 0) << "dnum = " << dnum; result_dimensions.push_back(dimension); } auto result_shape = ShapeUtil::MakeShapeWithDenseLayout( shape().element_type(), result_dimensions, LayoutUtil::MinorToMajor(shape())); ShapeUtil::CopyDynamicDimensions(&result_shape, shape()); Literal result_literal(result_shape); primitive_util::ArrayTypeSwitch<void>( [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; return SliceInternal<NativeT>(*this, start_indices, result_literal); }, result_shape.element_type()); return result_literal; } Literal LiteralBase::Clone() const { Literal result(shape()); TF_CHECK_OK(result.CopyFrom(*this)); return result; } std::unique_ptr<Literal> LiteralBase::CloneToUnique() const { auto result = std::make_unique<Literal>(shape()); TF_CHECK_OK(result->CopyFrom(*this)); return result; } bool LiteralBase::IsDetermined(const ShapeIndex& shape_index) const { return piece(shape_index).IsDetermined(); } bool LiteralBase::IsKnown(const ShapeIndex& shape_index) const { return piece(shape_index).IsKnown(); } std::string LiteralBase::GetAsString(absl::Span<const int64_t> multi_index, const ShapeIndex& shape_index) const { const Shape& subshape = ShapeUtil::GetSubshape(shape(), shape_index); CHECK(LayoutUtil::IsDenseArray(subshape)); return primitive_util::ArrayTypeSwitch<std::string>( [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, subshape.element_type()); } [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, std::optional<int64_t> LiteralBase::GetIntegralAsS64( absl::Span<const int64_t> multi_index) const { CHECK(LayoutUtil::IsDenseArray(shape())); return primitive_util::PrimitiveTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, std::optional<double> LiteralBase::GetAsDouble( absl::Span<const int64_t> multi_index) const { const Shape& s = shape(); CHECK(LayoutUtil::IsDenseArray(s)); return primitive_util::PrimitiveTypeSwitch<std::optional<double>>( [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, s.element_type()); } [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, std::optional<double> LiteralBase::GetSumAsDouble( absl::Span<const int64_t> linear_indices) const { const Shape& s = shape(); CHECK(LayoutUtil::IsDenseArray(s)); if (!primitive_util::IsFloatingPointType(s.element_type())) { return std::nullopt; } return primitive_util::FloatingPointTypeSwitch<double>( [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, s.element_type()); } [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, std::optional<complex128> LiteralBase::GetAsComplex128( absl::Span<const int64_t> multi_index) const { return primitive_util::PrimitiveTypeSwitch<std::optional<complex128>>( [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, absl::Status MutableLiteralBase::SetIntegralAsS64( absl::Span<const int64_t> multi_index, int64_t value) { CHECK(LayoutUtil::IsDenseArray(shape())); return primitive_util::PrimitiveTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, absl::Status MutableLiteralBase::SetFromDouble( absl::Span<const int64_t> multi_index, double value) { CHECK(LayoutUtil::IsDenseArray(shape())); if (!primitive_util::IsFloatingPointType(shape().element_type())) { return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); } primitive_util::FloatingPointTypeSwitch<void>( [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, shape().element_type()); return absl::OkStatus(); } [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, void PrintShape(bool print_layout, const Shape& shape, Printer* printer) { if (print_layout) { ShapeUtil::PrintHumanStringWithLayout(printer, shape); } else { ShapeUtil::PrintHumanString(printer, shape); } } void TuplePrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); printer->Append(oneline ? "( " : "(\n"); for (int i = 0; i < ShapeUtil::TupleElementCount(subshape); ++i) { ShapeIndex element_index = shape_index; element_index.push_back(i); if (i > 0) printer->Append(oneline ? ", " : ",\n"); PrintHelper(literal, element_index, print_shape, print_layout, oneline, printer); } printer->Append(oneline ? " )" : "\n)"); } void DenseArrayPrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); int64_t rank = subshape.rank(); const absl::string_view linebreak = oneline ? " " : "\n"; std::function<void(absl::Span<const int64_t> dimensions, std::vector<int64_t>*)> print_recursive = [&](absl::Span<const int64_t> dimensions, std::vector<int64_t>* accum_indices) { // dimensions.size() decreases by 1 at each recursive call, // and accum_indices->size() increases by 1. // Their sum is equal to the rank of the tensor. CHECK_EQ(rank, dimensions.size() + accum_indices->size()); auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; if (dimensions.empty()) { // Display predicates as 0s and 1s so that the string is more dense. std::string elem; if (subshape.element_type() == PRED && rank > 0) { elem = literal.Get<bool>(*accum_indices, shape_index) ? "1" : "0"; } else { elem = literal.GetAsString(*accum_indices, shape_index); } printer->Append(elem); } else { printer->Append(brace_to_string("{")); for (int i = 0; i < dimensions[0]; ++i) { accum_indices->push_back(i); print_recursive(dimensions.subspan(1), accum_indices); accum_indices->pop_back(); if (i < dimensions[0] - 1) { printer->Append(","); printer->Append(dimensions.size() > 1 ? linebreak : " "); } } printer->Append(brace_to_string("}")); } }; if (print_shape) { PrintShape(print_layout, subshape, printer); if (subshape.is_dynamic()) { printer->Append("("); for (int64_t i = 0; i < subshape.dimensions_size(); ++i) { printer->Append(literal.GetDynamicSize(i, shape_index)); if (i < subshape.dimensions_size() - 1) { printer->Append(","); } } printer->Append(")"); } printer->Append(" "); } std::vector<int64_t> indices = {}; std::vector<int64_t> dimensions; dimensions.reserve(subshape.rank()); for (int64_t i = 0; i < subshape.rank(); ++i) { dimensions.push_back(literal.GetDynamicSize(i, shape_index)); } print_recursive(dimensions, &indices); } print_recursive = [&](absl::Span<const int64_t> dimensions, std::vector<int64_t>* accum_indices) { // dimensions.size() decreases by 1 at each recursive call, // and accum_indices->size() increases by 1. // Their sum is equal to the rank of the tensor. CHECK_EQ(rank, dimensions.size() + accum_indices->size()); auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; if (dimensions.empty()) { // Display predicates as 0s and 1s so that the string is more dense. std::string elem; if (subshape.element_type() == PRED && rank > 0) { elem = literal.Get<bool>(*accum_indices, shape_index) ? "1" : "0"; } else { elem = literal.GetAsString(*accum_indices, shape_index); } printer->Append(elem); } else { printer->Append(brace_to_string("{")); for (int i = 0; i < dimensions[0]; ++i) { accum_indices->push_back(i); print_recursive(dimensions.subspan(1), accum_indices); accum_indices->pop_back(); if (i < dimensions[0] - 1) { printer->Append(","); printer->Append(dimensions.size() > 1 ? linebreak : " "); } } printer->Append(brace_to_string("}")); } }; auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; void PrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); CHECK(LayoutUtil::HasLayout(literal.shape())); CHECK(LayoutUtil::HasLayout(subshape)); if (subshape.IsTuple()) { TuplePrintHelper(literal, shape_index, print_shape, print_layout, oneline, printer); } else if (subshape.IsToken()) { printer->Append("token"); } else { CHECK(LayoutUtil::IsDenseArray(subshape)); if (literal.IsKnown(shape_index)) { DenseArrayPrintHelper(literal, shape_index, print_shape, print_layout, oneline, printer); } else { PrintShape(print_layout, subshape, printer); printer->Append(" "); if (literal.IsDetermined(shape_index)) { printer->Append("unknown"); } else { printer->Append("undetermined"); } } } } void LiteralBase::Print(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/false, /*oneline=*/false, printer); } void LiteralBase::PrintOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/false, /*oneline=*/true, printer); } void LiteralBase::PrintWithoutShape(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/false, /*print_layout=*/false, /*oneline=*/false, printer); } void LiteralBase::PrintWithoutShapeOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/false, /*print_layout=*/false, /*oneline=*/true, printer); } void LiteralBase::PrintWithLayout(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/true, /*oneline=*/false, printer); } void LiteralBase::PrintWithLayoutOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/true, /*oneline=*/true, printer); } std::string LiteralBase::ToString() const { StringPrinter printer; Print(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringOneline() const { StringPrinter printer; PrintOneline(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithoutShape() const { StringPrinter printer; PrintWithoutShape(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithoutShapeOneline() const { StringPrinter printer; PrintWithoutShapeOneline(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithLayout() const { StringPrinter printer; PrintWithLayout(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithLayoutOneline() const { StringPrinter printer; PrintWithLayoutOneline(&printer); return std::move(printer).ToString(); } void LiteralBase::EachCellAsString( absl::FunctionRef<void(absl::Span<const int64_t> indices, const std::string& value)> per_cell) const { if (ShapeUtil::IsZeroElementArray(shape())) { return; } auto indices = IndexUtil::LinearIndexToMultidimensionalIndex( shape(), /*linear_index=*/0); do { per_cell(indices, GetAsString(indices)); } while (IndexUtil::BumpIndices(shape(), absl::MakeSpan(indices))); } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { absl::StatusOr<Literal> ConvertSwitch(const LiteralBase& literal, PrimitiveType primitive_dest_type) { TF_RET_CHECK(LayoutUtil::IsDenseArray(literal.shape())); if (literal.shape().element_type() == primitive_dest_type) { return literal.Clone(); } // Source Array type requirement is ensured by IsDenseArray before. if (!primitive_util::IsArrayType(primitive_dest_type) || !primitive_util::IsArrayType(literal.shape().element_type())) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(literal.shape().element_type()), PrimitiveType_Name(primitive_dest_type)); } // At this point, we know both src & dst are array types, while src is not // complex type, so we can allocate the result literal here to avoid // duplicating it N^2 times in the conversion implementation. Literal result( ShapeUtil::ChangeElementType(literal.shape(), primitive_dest_type)); TF_RETURN_IF_ERROR(primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { return ConvertIfDestTypeMatches<primitive_type_constant>(literal, result); }, literal.shape().element_type())); return result; } absl::StatusOr<Literal> LiteralBase::Convert( PrimitiveType primitive_dest_type) const { return ConvertSwitch(*this, primitive_dest_type); } absl::StatusOr<Literal> LiteralBase::BitcastConvert( const Shape& dest_shape) const { if (ShapeUtil::ByteSizeOf(dest_shape) != ShapeUtil::ByteSizeOf(shape())) { return InvalidArgument( "Can not bitcast-convert from shape %s to a shape of different size %s", shape().ToString(), dest_shape.ToString()); } if (dest_shape.IsTuple() || shape().IsTuple()) { return InvalidArgument( "bitcast-convert is not valid for tuple shapes %s->%s", shape().ToString(), dest_shape.ToString()); } if (shape().is_dynamic() || dest_shape.is_dynamic()) { return InvalidArgument( "bitcast-convert is not valid for dynamic shape %s->%s", shape().ToString(), dest_shape.ToString()); } Literal out(dest_shape); std::memcpy(out.root_piece_.buffer(), root_piece().buffer(), root_piece().size_bytes_dense()); // Perform the reshape on little endian encoding even on big endian machines. if constexpr (!kLittleEndian) { // Swap byte ordering as per the input data type. size_t input_elem_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); TF_RETURN_IF_ERROR(tsl::ByteSwapArray( const_cast<char*>(out.root_piece().buffer()), input_elem_size, out.root_piece().size_bytes_dense() / input_elem_size)); // Swap byte ordering as per the output data type. size_t output_elem_size = ShapeUtil::ByteSizeOfPrimitiveType(dest_shape.element_type()); TF_RETURN_IF_ERROR(tsl::ByteSwapArray( const_cast<char*>(out.root_piece().buffer()), output_elem_size, out.root_piece().size_bytes_dense() / output_elem_size)); } return out; } absl::StatusOr<Literal> LiteralBase::ConvertToShape( const Shape& dest_shape) const { if (!dest_shape.IsTuple()) { return Convert(dest_shape.element_type()); } std::vector<Literal> elements; const auto tuple_element_count = ShapeUtil::TupleElementCount(shape()); elements.reserve(tuple_element_count); for (int i = 0; i < tuple_element_count; ++i) { auto element = LiteralSlice(*this, {i}); TF_ASSIGN_OR_RETURN( auto new_element, element.ConvertToShape(ShapeUtil::GetSubshape(dest_shape, {i}))); elements.push_back(std::move(new_element)); } return MutableLiteralBase::MoveIntoTuple(absl::MakeSpan(elements)); } /* static */ Literal MutableLiteralBase::MoveIntoTuple( absl::Span<Literal> elements) { std::vector<const Shape*> element_shapes; element_shapes.reserve(elements.size()); for (const Literal& element : elements) { element_shapes.push_back(&element.shape()); } Literal literal(ShapeUtil::MakeTupleShapeWithPtrs(element_shapes), /*allocate_arrays=*/false); for (int i = 0, end = elements.size(); i < end; ++i) { TF_CHECK_OK( literal.MoveFrom(std::move(elements[i]), /*dest_shape_index=*/{i})); } return literal; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualDynamicSize( const LiteralBase::Piece& other) const { DCHECK(ShapeUtil::Compatible(subshape(), other.subshape())); if (subshape().is_static()) { return true; } for (int64_t i = 0; i < subshape().rank(); ++i) { if (GetDynamicSize(i) != other.GetDynamicSize(i)) { return false; } } return true; } bool LiteralBase::Piece::EqualElements(const LiteralBase::Piece& other) const { if (subshape().is_static() && ShapeUtil::Equal(subshape(), other.subshape()) && subshape().IsArray()) { CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(size_bytes_dense(), other.size_bytes_dense()); if (primitive_util::IsSubByteNonPredType(subshape().element_type())) { CHECK(!primitive_util::IsFloatingPointType(subshape().element_type())); auto one_array = buffer(); auto two_array = other.buffer(); const int bits_per_element = primitive_util::BitWidth(subshape().element_type()); const uint8_t mask = LsbMask<uint8_t>(bits_per_element); for (int64_t i = 0; i < size_bytes_dense(); ++i) { if ((one_array[i] & mask) != (two_array[i] & mask)) return false; } return true; } return memcmp(buffer(), other.buffer(), size_bytes_dense()) == 0; } std::vector<int64_t> multi_index; return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeSrcT = NativeTypeOf<primitive_type_constant>; return EqualElementsInternal<NativeSrcT>(other, &multi_index); }, subshape().element_type()); } bool LiteralBase::Equal(const LiteralBase& other, bool layout_sensitive) const { // Checking the structure of tuple literals. Checks for dense arrays are // performed below. if (!ShapeUtil::EqualStructure(shape(), other.shape())) { return false; } return root_piece().ForEachSubpieceWithBool([&](const ShapeIndex& index, const Piece& piece) { const Piece& other_piece = other.piece(index); const Shape& subshape = piece.subshape(); const Shape& other_subshape = other_piece.subshape(); if (subshape.element_type() != other_subshape.element_type()) { return false; } if (!piece.subshape().IsArray()) { return true; } if (subshape.rank() != other_subshape.rank()) { return false; } if (layout_sensitive && (subshape.layout() != other_subshape.layout())) { return false; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (piece.GetDynamicSize(i) != other_piece.GetDynamicSize(i)) { return false; } } if (!piece.EqualElements(other_piece)) { return false; } return true; }); } return root_piece().ForEachSubpieceWithBool([&](const ShapeIndex& index, const Piece& piece) { const Piece& other_piece = other.piece(index); const Shape& subshape = piece.subshape(); const Shape& other_subshape = other_piece.subshape(); if (subshape.element_type() != other_subshape.element_type()) { return false; } if (!piece.subshape().IsArray()) { return true; } if (subshape.rank() != other_subshape.rank()) { return false; } if (layout_sensitive && (subshape.layout() != other_subshape.layout())) { return false; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (piece.GetDynamicSize(i) != other_piece.GetDynamicSize(i)) { return false; } } if (!piece.EqualElements(other_piece)) { return false; } return true; }); static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(std::complex<T> a, std::complex<T> b) { return EqualIncludingNan(a.real(), b.real()) && EqualIncludingNan(a.imag(), b.imag()); } static bool EqualIncludingNan(std::complex<T> a, std::complex<T> b) { return EqualIncludingNan(a.real(), b.real()) && EqualIncludingNan(a.imag(), b.imag()); } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } bool Literal::Piece::IsAll(const Literal& scalar) const { CHECK(ShapeUtil::IsScalar(scalar.shape())) << scalar.shape().ToString(); if (!subshape().IsArray()) { return false; } CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(subshape().element_type(), scalar.shape().element_type()); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, subshape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, int64_t Literal::Piece::CountAll(const Literal& scalar) const { CHECK(ShapeUtil::IsScalar(scalar.shape())) << scalar.shape().ToString(); if (!subshape().IsArray()) { return 0; } CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(subshape().element_type(), scalar.shape().element_type()); return primitive_util::ArrayTypeSwitch<int64_t>( [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, subshape().element_type()); } [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { bool LiteralBase::IsAll(const Literal& scalar) const { return root_piece().IsAll(scalar); } bool LiteralBase::IsAll(int8_t value) const { if (!shape().IsArray()) { return false; } PrimitiveType ty = shape().element_type(); if (primitive_util::IsFloatingPointType(ty)) { return IsAllFloatImpl(value, /*round_value=*/false); } if (primitive_util::IsUnsignedIntegralType(ty) && value < 0) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllFloat(float value) const { return IsAllFloatImpl(value, /*round_value=*/true); } bool LiteralBase::IsAllFloatImpl(float value, bool round_value) const { PrimitiveType ty = shape().element_type(); if (!primitive_util::IsFloatingPointType(ty)) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::FloatingPointTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllComplex(complex64 value) const { PrimitiveType ty = shape().element_type(); if (!primitive_util::IsComplexType(ty)) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::ComplexTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllFirst() const { if (!shape().IsArray()) { return false; } // Empty shapes are not all the first element since there is no first element. if (ShapeUtil::IsZeroElementArray(shape())) { return false; } absl::InlinedVector<int64_t, 4> start_indices(/*n=*/shape().rank(), 0); absl::InlinedVector<int64_t, 4> end_indices(/*n=*/shape().rank(), 1); Literal first = Slice(start_indices, end_indices); return IsAll(first.Reshape({}).value()); } bool LiteralBase::IsR1Iota() const { if (!shape().IsArray()) { return false; } CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); if (shape().rank() != 1) { return false; } return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, shape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, std::optional<int64_t> LiteralBase::IsR1StridedIota() const { if (!shape().IsArray() || shape().rank() != 1) { return std::nullopt; } CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); const int64_t elements = ShapeUtil::ElementsIn(shape()); const PrimitiveType type = shape().element_type(); if (elements <= 1 || !primitive_util::IsIntegralType(type)) { return std::nullopt; } return primitive_util::IntegralTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, bool LiteralBase::IsZero(absl::Span<const int64_t> indices) const { CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, shape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void LiteralBase::Piece::set_array_value_state(ArrayValueState state) { array_value_state_ = state; } LiteralBase::ArrayValueState LiteralBase::Piece::get_array_value_state() const { return array_value_state_; } void LiteralBase::Piece::WriteToProto(LiteralProto* proto) const { *proto->mutable_shape() = subshape().ToProto(); switch (subshape().element_type()) { case PRED: CopyToRepeatedField(proto->mutable_preds(), data<bool>()); break; case U2: *proto->mutable_u2s() = std::string( reinterpret_cast<const char*>(data<u2>().data()), size_bytes_dense()); break; case U4: *proto->mutable_u4s() = std::string( reinterpret_cast<const char*>(data<u4>().data()), size_bytes_dense()); break; case U8: proto->set_u8s(static_cast<const unsigned char*>(data<uint8_t>().data()), element_count()); break; case U16: *proto->mutable_u16s() = std::string(reinterpret_cast<const char*>(data<uint16_t>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_u16s()); } break; case U32: CopyToRepeatedField(proto->mutable_u32s(), data<uint32_t>()); break; case U64: CopyToRepeatedField(proto->mutable_u64s(), data<uint64_t>()); break; case S2: *proto->mutable_s2s() = std::string( reinterpret_cast<const char*>(data<s2>().data()), size_bytes_dense()); break; case S4: *proto->mutable_s4s() = std::string( reinterpret_cast<const char*>(data<s4>().data()), size_bytes_dense()); break; case S8: proto->set_s8s(static_cast<const signed char*>(data<int8_t>().data()), element_count()); break; case S16: *proto->mutable_s16s() = std::string(reinterpret_cast<const char*>(data<int16_t>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_s16s()); } break; case S32: CopyToRepeatedField(proto->mutable_s32s(), data<int32_t>()); break; case S64: CopyToRepeatedField(proto->mutable_s64s(), data<int64_t>()); break; case F8E5M2: *proto->mutable_f8e5m2s() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e5m2>().data()), size_bytes_dense()); break; case F8E4M3FN: *proto->mutable_f8e4m3fns() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3fn>().data()), size_bytes_dense()); break; case F8E4M3B11FNUZ: *proto->mutable_f8e4m3b11fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3b11fnuz>().data()), size_bytes_dense()); break; case F8E5M2FNUZ: *proto->mutable_f8e5m2fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e5m2fnuz>().data()), size_bytes_dense()); break; case F8E4M3FNUZ: *proto->mutable_f8e4m3fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3fnuz>().data()), size_bytes_dense()); break; case F16: *proto->mutable_f16s() = std::string(reinterpret_cast<const char*>(data<half>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_f16s()); } break; case BF16: *proto->mutable_bf16s() = std::string(reinterpret_cast<const char*>(data<bfloat16>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_bf16s()); } break; case F32: CopyToRepeatedField(proto->mutable_f32s(), data<float>()); break; case F64: CopyToRepeatedField(proto->mutable_f64s(), data<double>()); break; case C64: for (complex64 value : data<complex64>()) { proto->add_c64s(value.real()); proto->add_c64s(value.imag()); } break; case C128: for (complex128 value : data<complex128>()) { proto->add_c128s(value.real()); proto->add_c128s(value.imag()); } break; case TUPLE: case TOKEN: // Nothing to do but assign the shape which is done above. return; default: // TODO(b/111551621): Support serializing more PrimitiveTypes. LOG(FATAL) << "Unhandled primitive type " << PrimitiveType_Name(subshape().element_type()); } } const void* LiteralBase::Piece::untyped_data() const { DCHECK(LayoutUtil::IsDenseArray(subshape())) << ShapeUtil::HumanString(subshape()); return buffer(); } void* LiteralBase::Piece::untyped_data() { DCHECK(LayoutUtil::IsDenseArray(subshape())) << ShapeUtil::HumanString(subshape()); return buffer(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status LiteralBase::Piece::CopyFromProto(const LiteralProto& proto) { // These conditions should have been checked in // MutableLiteralBase::CreateFromProto. TF_RET_CHECK(proto.has_shape()); Shape shape(proto.shape()); TF_RET_CHECK(LayoutUtil::HasLayout(shape)); TF_RET_CHECK(ShapeUtil::Equal(shape, subshape())); switch (subshape().element_type()) { case PRED: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<bool>(), proto.preds())); break; case S2: { const std::string& s(proto.s2s()); TF_RET_CHECK(data<s2>().size() * sizeof(s2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case S4: { const std::string& s(proto.s4s()); TF_RET_CHECK(data<s4>().size() * sizeof(s4) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case S8: { auto s8_data = data<int8_t>(); TF_RET_CHECK(proto.s8s().size() == s8_data.size()); std::copy(proto.s8s().begin(), proto.s8s().end(), s8_data.begin()); break; } case S16: { const std::string& s(proto.s16s()); TF_RET_CHECK(data<int16_t>().size() * sizeof(int16_t) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case S32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<int32_t>(), proto.s32s())); break; case S64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<int64_t>(), proto.s64s())); break; case U2: { const std::string& s(proto.u2s()); TF_RET_CHECK(data<u2>().size() * sizeof(u2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case U4: { const std::string& s(proto.u4s()); TF_RET_CHECK(data<u4>().size() * sizeof(u4) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case U8: { auto u8_data = data<uint8_t>(); TF_RET_CHECK(proto.u8s().size() == u8_data.size()); std::copy(proto.u8s().begin(), proto.u8s().end(), u8_data.begin()); break; } case U16: { const std::string& s(proto.u16s()); TF_RET_CHECK(data<uint16_t>().size() * sizeof(uint16_t) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case U32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<uint32_t>(), proto.u32s())); break; case U64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<uint64_t>(), proto.u64s())); break; case F8E5M2: { const std::string& s(proto.f8e5m2s()); TF_RET_CHECK(data<tsl::float8_e5m2>().size() * sizeof(tsl::float8_e5m2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3FN: { const std::string& s(proto.f8e4m3fns()); TF_RET_CHECK(data<tsl::float8_e4m3fn>().size() * sizeof(tsl::float8_e4m3fn) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3B11FNUZ: { const std::string& s(proto.f8e4m3b11fnuzs()); TF_RET_CHECK(data<tsl::float8_e4m3b11fnuz>().size() * sizeof(tsl::float8_e4m3b11fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E5M2FNUZ: { const std::string& s(proto.f8e5m2fnuzs()); TF_RET_CHECK(data<tsl::float8_e5m2fnuz>().size() * sizeof(tsl::float8_e5m2fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3FNUZ: { const std::string& s(proto.f8e4m3fnuzs()); TF_RET_CHECK(data<tsl::float8_e4m3fnuz>().size() * sizeof(tsl::float8_e4m3fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F16: { const std::string& s(proto.f16s()); TF_RET_CHECK(data<half>().size() * sizeof(half) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case BF16: { const std::string& s(proto.bf16s()); TF_RET_CHECK(data<bfloat16>().size() * sizeof(bfloat16) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case F32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<float>(), proto.f32s())); break; case F64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<double>(), proto.f64s())); break; case C64: { auto complex_data = data<complex64>(); TF_RET_CHECK(proto.c64s_size() == complex_data.size() * 2); for (int64_t i = 0; i < complex_data.size(); ++i) { complex_data[i] = complex64{proto.c64s(i * 2), proto.c64s(i * 2 + 1)}; } break; } case C128: { auto complex_data = data<complex128>(); const int64_t complex_data_size_doubled = complex_data.size() * 2; TF_RET_CHECK(proto.c128s_size() == complex_data_size_doubled); for (int64_t i = 0, end = complex_data.size(); i < end; ++i) { complex_data[i] = complex128{proto.c128s(i * 2), proto.c128s(i * 2 + 1)}; } break; } case TUPLE: return InvalidArgument("Should not be called on tuple shapes: %s", ShapeUtil::HumanString(subshape())); default: return InvalidArgument("Is called on unsupported shape: %s", ShapeUtil::HumanString(subshape())); } return absl::OkStatus(); } bool LiteralBase::Piece::IsKnown() const { if (array_value_state_ != ArrayValueState::kKnown) { return false; } if (subshape().IsTuple()) { bool are_all_leaf_arrays_known = true; ForEachSubpiece([&are_all_leaf_arrays_known](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_known &= piece.IsKnown(); }); return are_all_leaf_arrays_known; } return true; } ForEachSubpiece([&are_all_leaf_arrays_known](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_known &= piece.IsKnown(); }); bool LiteralBase::Piece::IsDetermined() const { if (array_value_state_ == ArrayValueState::kUndetermined) { return false; } if (subshape().IsTuple()) { bool are_all_leaf_arrays_determined = true; ForEachSubpiece([&are_all_leaf_arrays_determined](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_determined &= piece.IsDetermined(); }); return are_all_leaf_arrays_determined; } return true; } ForEachSubpiece([&are_all_leaf_arrays_determined](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_determined &= piece.IsDetermined(); }); LiteralProto LiteralBase::ToProto() const { LiteralProto proto; root_piece().ForEachSubpiece( [&](const ShapeIndex& index, const Piece& piece) { LiteralProto* proto_piece = &proto; for (int64_t i : index) { while (proto_piece->tuple_literals_size() <= i) { proto_piece->add_tuple_literals(); } proto_piece = proto_piece->mutable_tuple_literals(i); } piece.WriteToProto(proto_piece); }); return proto; } [&](const ShapeIndex& index, const Piece& piece) { LiteralProto* proto_piece = &proto; for (int64_t i : index) { while (proto_piece->tuple_literals_size() <= i) { proto_piece->add_tuple_literals(); } proto_piece = proto_piece->mutable_tuple_literals(i); } piece.WriteToProto(proto_piece); }); const void* LiteralBase::untyped_data(const ShapeIndex& shape_index) const { return piece(shape_index).untyped_data(); } void* MutableLiteralBase::untyped_data(const ShapeIndex& shape_index) { return piece(shape_index).untyped_data(); } int64_t LiteralBase::size_bytes(const ShapeIndex& shape_index) const { return piece(shape_index).size_bytes_dense(); } std::string LiteralBase::GetR1U8AsString() const { CHECK(shape().IsArray()); CHECK_EQ(shape().rank(), 1); CHECK_EQ(shape().element_type(), U8); return std::string(absl::bit_cast<const char*>(data<uint8_t>().data()), ShapeUtil::ElementsIn(shape())); } void MutableBorrowingLiteral::CopyPieceSubtree(const Shape& shape, const Piece* src_piece, Piece* dest_piece) { DCHECK(ShapeUtil::Equal(src_piece->subshape(), dest_piece->subshape())) << "src_piece has shape: " << ShapeUtil::HumanString(src_piece->subshape()) << "dest_piece has shape: " << ShapeUtil::HumanString(dest_piece->subshape()); dest_piece->set_array_value_state(src_piece->get_array_value_state()); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); Piece child_piece; child_piece.set_subshape(&subshape); CopyPieceSubtree(subshape, &src_piece->child(i), &child_piece); dest_piece->emplace_back(std::move(child_piece)); } } else if (shape.IsArray()) { dest_piece->set_buffer(const_cast<char*>(src_piece->buffer())); } } MutableLiteralBase::~MutableLiteralBase() = default; MutableBorrowingLiteral::MutableBorrowingLiteral( const MutableBorrowingLiteral& literal) : MutableLiteralBase() { shape_ = literal.shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.root_piece(), root_piece_); } MutableBorrowingLiteral& MutableBorrowingLiteral::operator=( const MutableBorrowingLiteral& literal) { shape_ = literal.shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.root_piece(), root_piece_); return *this; } MutableBorrowingLiteral::MutableBorrowingLiteral(MutableLiteralBase* literal) : MutableLiteralBase() { shape_ = literal->shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal->root_piece(), root_piece_); } MutableBorrowingLiteral::MutableBorrowingLiteral( MutableBorrowingLiteral literal, const ShapeIndex& view_root) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(literal.piece(view_root).subshape()); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.piece(view_root), root_piece_); } MutableBorrowingLiteral::MutableBorrowingLiteral(const char* src_buf_ptr, const Shape& shape) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(shape); CHECK(LayoutUtil::HasLayout(*shape_)); CHECK(!shape_->IsTuple()); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); root_piece_->set_buffer(const_cast<char*>(src_buf_ptr)); } MutableBorrowingLiteral::MutableBorrowingLiteral(absl::Span<char*> src_buf_ptrs, const Shape& shape) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(shape); if (!shape_->IsTuple()) { CHECK_EQ(src_buf_ptrs.size(), 1); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); root_piece_->set_buffer(const_cast<char*>(src_buf_ptrs[0])); } else { CHECK(!ShapeUtil::IsNestedTuple(*shape_)); CHECK_EQ(src_buf_ptrs.size(), ShapeUtil::TupleElementCount(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); for (int i = 0; i < src_buf_ptrs.size(); ++i) { Piece child_piece; const auto& src_shape = shape_->tuple_shapes(i); CHECK(src_shape.IsArray()); child_piece.set_subshape(&src_shape); child_piece.set_buffer(src_buf_ptrs[i]); root_piece_->emplace_back(std::move(child_piece)); } } } MutableBorrowingLiteral::MutableBorrowingLiteral(ShapeTree<char*> src_buf_ptrs) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(src_buf_ptrs.shape()); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); BuildPieceSubtree(*shape_, root_piece_); root_piece_->ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); } [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); MutableBorrowingLiteral::~MutableBorrowingLiteral() { if (root_piece_ != nullptr) { delete root_piece_; } } LiteralSlice::LiteralSlice(const LiteralBase& literal) : LiteralBase(), root_piece_(&literal.root_piece()) {} LiteralSlice::LiteralSlice(const LiteralBase& literal, const ShapeIndex& view_root) : LiteralBase(), root_piece_(&literal.piece(view_root)) {} BorrowingLiteral::BorrowingLiteral(const char* src_buf_ptr, const Shape& shape) : LiteralBase(), shape_(std::make_unique<Shape>(shape)) { CHECK(shape_->IsArray()); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); root_piece_.set_buffer(const_cast<char*>(src_buf_ptr)); } BorrowingLiteral::BorrowingLiteral(absl::Span<const char* const> src_buf_ptrs, const Shape& shape) : LiteralBase(), shape_(std::make_unique<Shape>(shape)) { CHECK(shape_->IsTuple()); CHECK(!ShapeUtil::IsNestedTuple(*shape_)); CHECK_EQ(src_buf_ptrs.size(), ShapeUtil::TupleElementCount(*shape_)); root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); BuildPieceSubtree(*shape_, &root_piece_); for (int i = 0, end = src_buf_ptrs.size(); i < end; ++i) { const auto& src_shape = shape_->tuple_shapes(i); CHECK(src_shape.IsArray()); root_piece_.child(i).set_buffer(const_cast<char*>(src_buf_ptrs[i])); } } BorrowingLiteral::BorrowingLiteral(ShapeTree<const char*> src_buf_ptrs) : LiteralBase(), shape_(std::make_unique<Shape>(src_buf_ptrs.shape())) { root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); BuildPieceSubtree(*shape_, &root_piece_); root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); } [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); });
#include "xla/literal.h" #include <algorithm> #include <cmath> #include <complex> #include <cstdint> #include <functional> #include <limits> #include <random> #include <string> #include <tuple> #include <utility> #include <vector> #include "absl/base/casts.h" #include "absl/hash/hash.h" #include "absl/random/random.h" #include "absl/status/status.h" #include "absl/strings/match.h" #include "absl/types/span.h" #include "xla/array.h" #include "xla/array2d.h" #include "xla/array3d.h" #include "xla/array4d.h" #include "xla/index_util.h" #include "xla/layout.h" #include "xla/layout_util.h" #include "xla/literal_util.h" #include "xla/primitive_util.h" #include "xla/shape.h" #include "xla/shape_tree.h" #include "xla/shape_util.h" #include "xla/test.h" #include "xla/types.h" #include "xla/util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/errors.h" #include "tsl/platform/logging.h" // IWYU pragma: keep #include "tsl/platform/macros.h" #include "tsl/platform/ml_dtypes.h" #include "tsl/platform/statusor.h" #include "tsl/platform/test_benchmark.h" class LiteralUtilTest : public ::testing::Test { protected: LiteralUtilTest() { Array4D<float> arr4d({ // clang-format off { // i0=0 { // i1=0 {1, 2, 3}, // i2=0 {4, 5, 6}, // i2=1 {7, 8, 9}, // i2=2 }, { // i1=1 {11, 12, 13}, {14, 15, 16}, {17, 18, 19}, }, }, { // i0=1 { // i1=0 {101, 102, 103}, {104, 105, 106}, {107, 108, 109}, }, { // i1=1 {201, 202, 203}, // i2=0 {204, 205, 206}, // i2=1 {207, 208, 209}, // i2=2 }, }, // clang-format on }); layout_r2_dim0major_ = LayoutUtil::MakeLayout({1, 0}); layout_r2_dim0minor_ = LayoutUtil::MakeLayout({0, 1}); layout_r3_dim0major_ = LayoutUtil::MakeLayout({2, 1, 0}); layout_r3_dim0minor_ = LayoutUtil::MakeLayout({0, 1, 2}); layout_r4_dim0major_ = LayoutUtil::MakeLayout({3, 2, 1, 0}); layout_r4_dim0minor_ = LayoutUtil::MakeLayout({0, 1, 2, 3}); literal_r4_2x2x3x3_dim0major_ = LiteralUtil::CreateR4FromArray4DWithLayout<float>(arr4d, layout_r4_dim0major_); literal_r4_2x2x3x3_dim0minor_ = LiteralUtil::CreateR4FromArray4DWithLayout<float>(arr4d, layout_r4_dim0minor_); } Layout layout_r2_dim0major_; Layout layout_r2_dim0minor_; Layout layout_r3_dim0major_; Layout layout_r3_dim0minor_; Layout layout_r4_dim0major_; Layout layout_r4_dim0minor_; Literal literal_r4_2x2x3x3_dim0major_; Literal literal_r4_2x2x3x3_dim0minor_; }; TEST_F(LiteralUtilTest, CopyFromArrays) { auto scalar_42 = LiteralUtil::CreateR0<float>(42.0); auto scalar_123 = LiteralUtil::CreateR0<float>(123.0); EXPECT_NE(scalar_42, scalar_123); TF_ASSERT_OK(scalar_42.CopyFrom(scalar_123, /*dest_shape_index=*/{}, /*src_shape_index=*/{})); EXPECT_EQ(scalar_42, scalar_123); EXPECT_EQ(scalar_42.Get<float>({}), 123.0f); auto matrix_1234 = LiteralUtil::CreateR2<float>({{1.0, 2.0}, {3.0, 4.0}}); auto matrix_5678 = LiteralUtil::CreateR2<float>({{5.0, 6.0}, {7.0, 8.0}}); EXPECT_NE(matrix_1234, matrix_5678); EXPECT_EQ(matrix_1234.Get<float>({0, 0}), 1.0f); TF_ASSERT_OK(matrix_1234.CopyFrom(matrix_5678, /*dest_shape_index=*/{}, /*src_shape_index=*/{})); EXPECT_EQ(matrix_1234, matrix_5678); EXPECT_EQ(matrix_1234.Get<float>({0, 0}), 5.0f); }
LiteralUtilTest_CopyFromDifferentShapes
xla/literal_test.cc
bool LiteralProtoHasValues(const LiteralProto& proto) { return !proto.s2s().empty() || !proto.s4s().empty() || !proto.s8s().empty() || !proto.s16s().empty() || proto.s32s_size() || proto.s64s_size() || !proto.u2s().empty() || !proto.u4s().empty() || !proto.u8s().empty() || !proto.u16s().empty() || proto.u32s_size() || proto.u64s_size() || !proto.f8e5m2s().empty() || !proto.f8e4m3fns().empty() || !proto.f8e4m3b11fnuzs().empty() || !proto.f8e5m2fnuzs().empty() || !proto.f8e4m3fnuzs().empty() || !proto.f16s().empty() || !proto.bf16s().empty() || proto.f32s_size() || proto.f64s_size() || proto.c64s_size() || proto.c128s_size() || proto.preds_size() || proto.tuple_literals_size(); } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } const Shape& ScalarShapeImpl() { static_assert(primitive_util::IsArrayType(kType), "Not a valid type for a scalar."); static const Shape* shape = [] { auto shape = new Shape(kType, {}, {}, {}); shape->mutable_layout(); return shape; }(); return *shape; } static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { static const Shape* shape = [] { const Shape& NilShape() { static const Shape* shape = new Shape(TUPLE, {}, {}, {}); return *shape; } const Shape* TryInternShape(const Shape& shape) { if (shape.IsTuple() && shape.tuple_shapes_size() == 0) { return &NilShape(); } if (shape.IsArray() && shape.dimensions_size() == 0 && shape.is_static() && shape.layout().tiles_size() == 0 && shape.layout().memory_space() == 0) { return &ScalarShape(shape.element_type()); } return nullptr; } StrideConfig::StrideConfig(const Shape& source_shape, const Shape& dest_shape, absl::Span<const int64_t> dimensions) : dimensions(dimensions), base(dimensions.size(), 0), step(dimensions.size(), 1) { if (!dimensions.empty()) { // Selects the shape with the largest minor dimension as the one upon // which to run the tight stride loop. if (dimensions[LayoutUtil::Minor(source_shape.layout(), 0)] >= dimensions[LayoutUtil::Minor(dest_shape.layout(), 0)]) { minor_dimension = LayoutUtil::Minor(source_shape.layout(), 0); dest_stride = IndexUtil::GetDimensionStride(dest_shape, minor_dimension); } else { minor_dimension = LayoutUtil::Minor(dest_shape.layout(), 0); source_stride = IndexUtil::GetDimensionStride(source_shape, minor_dimension); } minor_loop_size = dimensions[minor_dimension]; step[minor_dimension] = minor_loop_size; } } LiteralBase::~LiteralBase() = default; const Shape& LiteralBase::shape() const { return root_piece().subshape(); } const char* LiteralBase::Piece::buffer() const { // std::visit is avoided here due to its code size issues. if (auto* r = std::get_if<DenseRep>(&rep_)) { return r->data; } if (auto* r = std::get_if<DenseInlinedRep>(&rep_)) { return r->data; } DCHECK(std::holds_alternative<TupleRep>(rep_) || std::holds_alternative<Uninitialized>(rep_)); return nullptr; } const LiteralBase::Piece& LiteralBase::piece( const ShapeIndex& shape_index) const { const Piece* piece = &root_piece(); for (const auto i : shape_index) { DCHECK_GE(i, 0); DCHECK_LT(i, piece->children_size()); piece = &piece->child(i); } return *piece; } std::ostream& operator<<(std::ostream& out, const Literal& literal) { out << literal.ToString(); return out; } Shape* MutableLiteralBase::mutable_shape_do_not_use() { const Shape* const_shape = shape_.get(); if (!shape_.OwnsPtr()) { shape_ = MaybeOwningShapePtr(std::make_unique<Shape>(*shape_)); } Shape* shape = shape_.get_mutable(); if (shape != const_shape) { std::function<void(const Shape&, Piece*)> set_piece_shapes = [&set_piece_shapes](const Shape& shape, Piece* piece) { piece->set_subshape(&shape); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); set_piece_shapes(subshape, &piece->child(i)); } } }; set_piece_shapes(*shape, &mutable_root_piece()); } return shape; } [&set_piece_shapes](const Shape& shape, Piece* piece) { piece->set_subshape(&shape); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); set_piece_shapes(subshape, &piece->child(i)); } } }; Literal::Literal() : Literal(NilShape()) {} Literal::Literal(const Shape& shape) : Literal(shape, /*allocate_arrays=*/true) {} void Literal::SetShape(const Shape& shape) { Shape shape_storage; const Shape* shape_ptr = &shape; if (LayoutUtil::HasCustomElementSizeInBits(shape)) { shape_storage = shape; shape_storage.mutable_layout()->set_element_size_in_bits(0); shape_ptr = &shape_storage; } if (const Shape* intered_shape_ptr = TryInternShape(*shape_ptr)) { shape_ = intered_shape_ptr; } else { shape_ = std::make_unique<Shape>(*shape_ptr); } } void Literal::SetPiece(const Shape& shape, Piece* piece, bool allocate_arrays, ArrayValueState leaf_array_value_state) { if (shape.IsTuple()) { for (const Shape& subshape : shape.tuple_shapes()) { Piece child_piece; child_piece.set_subshape(&subshape); SetPiece(subshape, &child_piece, allocate_arrays, leaf_array_value_state); piece->emplace_back(std::move(child_piece)); } } else if (shape.IsArray()) { DCHECK(LayoutUtil::IsDenseArray(shape)) << "literal array storage is currently only supported for dense " "arrays: " << shape; piece->set_array_value_state(leaf_array_value_state); if (leaf_array_value_state == LiteralBase::ArrayValueState::kKnown && allocate_arrays) { piece->AllocateBuffers(); } } } Literal::Literal(const Shape& shape, bool allocate_arrays, ArrayValueState leaf_array_value_state) : MutableLiteralBase() { SetShape(shape); CHECK(leaf_array_value_state != ArrayValueState::kKnown || LayoutUtil::HasLayout(*shape_)); root_piece_.set_subshape(shape_.get()); CHECK(&root_piece_.subshape() == shape_.get()); SetPiece(*shape_, &root_piece_, allocate_arrays, leaf_array_value_state); } Literal::~Literal() { DeallocateBuffers(); } void Literal::DeallocateBuffers() { root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { piece->DeallocateBuffers(); }); } Literal::Literal(Literal&& other) : MutableLiteralBase() { *this = std::move(other); } Literal& Literal::operator=(Literal&& other) { DCHECK(&other.root_piece_.subshape() == other.shape_.get()); using std::swap; swap(shape_, other.shape_); swap(root_piece_, other.root_piece_); DCHECK(&root_piece_.subshape() == shape_.get()); return *this; } Literal LiteralBase::CreateFromShape(const Shape& shape) { Literal literal(shape); literal.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (piece->subshape().IsArray()) { memset(piece->untyped_data(), 0, piece->size_bytes_dense()); } }); return literal; } [&](const ShapeIndex& index, Piece* piece) { if (piece->subshape().IsArray()) { memset(piece->untyped_data(), 0, piece->size_bytes_dense()); } }); Literal LiteralBase::CreateFromShapeWithUnknownLeafArrays(const Shape& shape) { Literal literal(shape, /*allocate_arrays=*/false, ArrayValueState::kUnknown); return literal; } Literal LiteralBase::CreateFromShapeWithUndeterminedLeafArrays( const Shape& shape) { Literal literal(shape, /*allocate_arrays=*/false, ArrayValueState::kUndetermined); return literal; } int32_t LiteralBase::GetDynamicSize(int64_t dim_index) const { return GetDynamicSize(dim_index, {}); } int32_t LiteralBase::GetDynamicSize(int64_t dim_index, const ShapeIndex& shape_index) const { return piece(shape_index).GetDynamicSize(dim_index); } std::optional<int64_t> LiteralBase::GetFirstInteger() const { if (!primitive_util::IsIntegralType(shape().element_type())) { return std::nullopt; } return primitive_util::IntegralTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; auto first_element = GetFirstElement<NativeT>(); if constexpr (std::is_same_v<NativeT, uint64_t>) { int64_t v = static_cast<int64_t>(first_element); if (v < 0) { return std::nullopt; } } return first_element; }, void LiteralBase::BuildPieceSubtree(const Shape& shape, Piece* piece) { CHECK(shape.IsTuple()); for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); Piece child_piece; child_piece.set_subshape(&subshape); if (subshape.IsTuple()) { BuildPieceSubtree(subshape, &child_piece); } piece->emplace_back(std::move(child_piece)); } } absl::Status LiteralBase::SerializeToString(std::string* output) const { ShapeProto shape_proto = shape().ToProto(); TF_ASSIGN_OR_RETURN(int64_t size, ShapeUtil::SerializedSizeWithProto(shape(), shape_proto)); output->resize(size); return SerializeWithShapeProto(shape_proto, output->data()); } absl::StatusOr<std::string> LiteralBase::SerializeAsString() const { std::string result; TF_RETURN_IF_ERROR(SerializeToString(&result)); return std::move(result); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } absl::Status MutableLiteralBase::CopySliceFromInternal( const LiteralBase& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { auto linear_index = [](const Shape& shape, absl::Span<const int64_t> multi_index) { return IndexUtil::MultidimensionalIndexToLinearIndex(shape, multi_index); }; // `this->` is needed to workaround MSVC bug: #16882 NativeT* dest_data = this->data<NativeT>().data(); const NativeT* src_data = src_literal.data<NativeT>().data(); if (src_literal.shape().rank() == 0 || shape().rank() == 0) { // If any of the two shapes are scalars, just assign the value once. TF_RET_CHECK(copy_size.empty()); dest_data[linear_index(shape(), dest_base)] = src_data[linear_index(src_literal.shape(), src_base)]; } else if (!ShapeUtil::IsZeroElementArray(shape()) && !ShapeUtil::IsZeroElementArray(src_literal.shape()) && absl::c_none_of(copy_size, [](auto d) { return d == 0; })) { // Perform copy if none of src, dest and copy_size has dimensions with zero // element, otherwise it's a no-op. TF_RET_CHECK(src_base.size() == dest_base.size()); TF_RET_CHECK(src_base.size() == copy_size.size()); // Scan the source from minor, stepping in copy size blocks, then within // the index enumeration functor, do a strided copy advancing source index // by one (walking through the minor dimension), and destination index by // proper stride size at the matching dimension. DimensionVector src_indexes(src_base.size(), 0); DimensionVector dest_indexes(dest_base.size(), 0); StrideConfig stride_config(src_literal.shape(), shape(), copy_size); auto copy_proc = [&](absl::Span<const int64_t> indexes) { // Map from multi-dimensional index, to source index. std::transform(indexes.begin(), indexes.end(), src_base.begin(), src_indexes.begin(), std::plus<int64_t>()); // Map from multi-dimensional index, to destination index. std::transform(indexes.begin(), indexes.end(), dest_base.begin(), dest_indexes.begin(), std::plus<int64_t>()); int64_t src_index = linear_index(src_literal.shape(), src_indexes); int64_t dest_index = linear_index(shape(), dest_indexes); StridedCopy(dest_data + dest_index, stride_config.dest_stride, src_data + src_index, stride_config.source_stride, stride_config.minor_loop_size); return true; }; ShapeUtil::ForEachIndex(src_literal.shape(), stride_config.base, stride_config.dimensions, stride_config.step, copy_proc); } return absl::OkStatus(); } auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { auto copy_proc = [&](absl::Span<const int64_t> indexes) { void MutableLiteralBase::CopyElementFrom(const LiteralSlice& src_literal, absl::Span<const int64_t> src_index, absl::Span<const int64_t> dest_index) { DCHECK(LayoutUtil::IsDenseArray(shape())); DCHECK_EQ(shape().element_type(), src_literal.shape().element_type()); const int64_t src_linear_index = IndexUtil::MultidimensionalIndexToLinearIndex(src_literal.shape(), src_index); const int64_t dest_linear_index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), dest_index); const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); char* dest_address = static_cast<char*>(untyped_data()) + dest_linear_index * primitive_size; const char* source_address = static_cast<const char*>(src_literal.untyped_data()) + src_linear_index * primitive_size; if (dest_address != source_address) { memcpy(dest_address, source_address, primitive_size); } } /* static */ absl::StatusOr<Literal> MutableLiteralBase::CreateFromProto( const LiteralProto& proto, bool prohibit_empty_literal) { if (!proto.has_shape()) { return InvalidArgument("LiteralProto has no shape"); } Shape shape(proto.shape()); if (ShapeUtil::HasPrimitiveType(shape, OPAQUE_TYPE)) { return InvalidArgument( "Literal shape cannot include OPAQUE_TYPE sub-shape"); } if (!LayoutUtil::HasLayout(shape)) { return InvalidArgument("LiteralProto has no layout"); } if (LayoutUtil::IsSparseArray(shape)) { return Unimplemented("Sparse literals are not supported"); } TF_RETURN_IF_ERROR(ShapeUtil::ValidateShapeWithOptionalLayout(shape)); Literal literal(shape); TF_RETURN_IF_ERROR(literal.root_piece_.ForEachMutableSubpieceWithStatus( [&](const ShapeIndex& index, Piece* piece) -> absl::Status { const LiteralProto* proto_element = &proto; for (int64_t i : index) { CHECK(i < proto_element->tuple_literals_size()); proto_element = &proto_element->tuple_literals(i); } if (piece->subshape().IsTuple()) { if (proto_element->tuple_literals_size() != ShapeUtil::TupleElementCount(piece->subshape())) { return InvalidArgument( "Expected %d tuple elements in LiteralProto, has %d", ShapeUtil::TupleElementCount(piece->subshape()), proto_element->tuple_literals_size()); } return absl::OkStatus(); } if (piece->subshape().element_type() == TOKEN) { return absl::OkStatus(); } CHECK(piece->subshape().IsArray()); // When prohibit_empty_literal is false (allowing literal with no // values), only copy from proto if the literal proto has values. This // mode is used for a learned cost model. if (prohibit_empty_literal || LiteralProtoHasValues(*proto_element)) { TF_RETURN_IF_ERROR(piece->CopyFromProto(*proto_element)); } return absl::OkStatus(); })); return std::move(literal); } TF_RETURN_IF_ERROR(literal.root_piece_.ForEachMutableSubpieceWithStatus( Literal Literal::SubLiteral(ShapeIndexView shape_index) { if (!shape_index.empty()) { auto decomposed = this->DecomposeTuple(); return decomposed.at(shape_index.front()) .SubLiteral(shape_index.subspan(1)); } else { return std::move(*this); } } std::vector<Literal> Literal::DecomposeTuple() { CHECK(shape().IsTuple()); std::vector<Literal> elements; const auto tuple_element_count = ShapeUtil::TupleElementCount(shape()); elements.reserve(tuple_element_count); for (int i = 0; i < tuple_element_count; ++i) { elements.push_back(Literal(ShapeUtil::GetSubshape(shape(), {i}), /*allocate_arrays=*/false)); Literal& element = elements.back(); element.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* dest_piece) { if (dest_piece->subshape().IsTuple()) { return; } ShapeIndex src_index = {i}; for (int64_t j : index) { src_index.push_back(j); } Piece& src_piece = piece(src_index); // Move the respective buffer over to the element Literal. dest_piece->MoveDataFrom(src_piece); }); } // Set this literal to be nil-shaped. *this = Literal(); return elements; } [&](const ShapeIndex& index, Piece* dest_piece) { if (dest_piece->subshape().IsTuple()) { return; } ShapeIndex src_index = {i}; for (int64_t j : index) { src_index.push_back(j); } Piece& src_piece = piece(src_index); // Move the respective buffer over to the element Literal. dest_piece->MoveDataFrom(src_piece); }); void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } void CopyElementsBetween(absl::Span<NativeT> dest, absl::Span<const NativeT> src, const Shape& dest_shape, const Shape& src_shape) { DCHECK(LayoutUtil::IsDenseArray(dest_shape)); DCHECK(LayoutUtil::IsDenseArray(src_shape)); DCHECK(ShapeUtil::Compatible(dest_shape, src_shape)); if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } std::vector<int64_t> index(dest_shape.rank()); do { dest[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src[IndexUtil::MultidimensionalIndexToLinearIndex(src_shape, index)]; } while (IndexUtil::BumpIndices(dest_shape, absl::MakeSpan(index))); } int32_t LiteralBase::Piece::GetDynamicSize(int64_t dim_index) const { CHECK(LayoutUtil::IsDenseArray(subshape())); if (!subshape_->is_dynamic_dimension(dim_index)) { // This is a static dimension, return size. return subshape_->dimensions(dim_index); } return dynamic_size_buffer()[dim_index]; } void LiteralBase::Piece::SetDynamicSize(int64_t dim_index, int32_t size) { CHECK(LayoutUtil::IsDenseArray(subshape())); CHECK(subshape_->is_dynamic_dimension(dim_index)); dynamic_size_buffer()[dim_index] = size; } void LiteralBase::Piece::AllocateBuffers() { const int64_t bytes = total_bytes_dense(); if (bytes > kMaxInlinedBytes) { CHECK_EQ(buffer(), nullptr); rep_.emplace<DenseRep>(); set_buffer( static_cast<char*>(tsl::port::AlignedMalloc(bytes, kMinimumAlignment))); } else { rep_.emplace<DenseInlinedRep>(); } } void LiteralBase::Piece::DeallocateBuffers() { if (auto* array_rep = GetDenseRep()) { tsl::port::AlignedFree(array_rep->data); rep_.emplace<Uninitialized>(); } } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } void LiteralBase::Piece::CopyElementsWithDynamicBound( const LiteralBase::Piece& src) { auto& dest_shape = subshape(); auto& src_shape = src.subshape(); // At least one shape has to be static as bound. CHECK(dest_shape.is_static() || src_shape.is_static()); auto& bound_shape = dest_shape.is_static() ? src_shape : dest_shape; if (ShapeUtil::IsZeroElementArray(dest_shape)) { return; } if (dest_shape.rank() == 1) { // Fast path for rank 1 arrays. int64_t count = std::min(GetDynamicSize(0), src.GetDynamicSize(0)); std::copy_n(src.data<NativeT>().begin(), count, data<NativeT>().begin()); return; } std::vector<int64_t> index(dest_shape.rank()); do { bool out_of_bound = false; for (int64_t i = 0; i < index.size(); ++i) { // Do not copy elements beyond dynamic bound. if (index[i] >= GetDynamicSize(i) || index[i] >= src.GetDynamicSize(i)) { out_of_bound = true; } } if (out_of_bound) { continue; } data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex(dest_shape, index)] = src.data<NativeT>()[IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, index)]; } while (IndexUtil::BumpIndices(bound_shape, absl::MakeSpan(index))); } absl::Status LiteralBase::Piece::CopyFrom(const LiteralBase::Piece& src, bool only_dynamic_bound) { CHECK(subshape_ != nullptr); CHECK(src.subshape_ != nullptr); CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK(LayoutUtil::IsDenseArray(src.subshape())) << __func__ << " is only supported for dense arrays: " << src.subshape(); if (!only_dynamic_bound) { CHECK(ShapeUtil::Compatible(subshape(), src.subshape())); } if (src.array_value_state_ == ArrayValueState::kUnknown || src.array_value_state_ == ArrayValueState::kUndetermined) { if (array_value_state_ == ArrayValueState::kKnown) { DeallocateBuffers(); } array_value_state_ = src.array_value_state_; return absl::OkStatus(); } else { CHECK(src.array_value_state_ == ArrayValueState::kKnown); if (array_value_state_ == ArrayValueState::kUndetermined || array_value_state_ == ArrayValueState::kUnknown) { AllocateBuffers(); } array_value_state_ = src.array_value_state_; } if (ShapeUtil::Equal(subshape(), src.subshape())) { // If the layouts are equal it's faster just to memcpy. memcpy(buffer(), src.buffer(), src.size_bytes_dense()); } else { std::vector<int64_t> origin(subshape().rank(), 0); primitive_util::ArrayTypeSwitch<void>( [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, subshape().element_type()); } DCHECK_EQ(dynamic_size_buffer_bytes(), src.dynamic_size_buffer_bytes()); if (subshape().is_dynamic() && src.subshape().is_dynamic()) { memcpy(dynamic_size_buffer(), src.dynamic_size_buffer(), src.dynamic_size_buffer_bytes()); } return absl::OkStatus(); } [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, [&](auto primitive_type_constant) { using NativeT = NativeTypeOf<primitive_type_constant>; if (only_dynamic_bound) { CopyElementsWithDynamicBound<NativeT>(src); } else { CopyElementsBetween<NativeT>(this->data<NativeT>(), src.data<NativeT>(), subshape(), src.subshape()); } }, void MutableLiteralBase::SetDynamicSize(int64_t dim_index, int32_t size) { return SetDynamicSize(dim_index, {}, size); } void MutableLiteralBase::SetDynamicSize(int64_t dim_index, const ShapeIndex& shape_index, int32_t size) { Shape* subshape = ShapeUtil::GetMutableSubshape(mutable_shape_do_not_use(), shape_index); CHECK(LayoutUtil::IsDenseArray(*subshape)) << __func__ << " is only supported for dense arrays: " << *subshape; CHECK_GE(subshape->dimensions(dim_index), size); subshape->set_dynamic_dimension(dim_index, true); CHECK_EQ(&piece(shape_index).subshape(), subshape); piece(shape_index).SetDynamicSize(dim_index, size); } absl::Status MutableLiteralBase::CopyFrom(const LiteralSlice& src_literal, const ShapeIndex& dest_shape_index, const ShapeIndex& src_shape_index, bool only_dynamic_bound) { const Shape& dest_subshape = ShapeUtil::GetSubshape(shape(), dest_shape_index); const Shape& src_subshape = ShapeUtil::GetSubshape(src_literal.shape(), src_shape_index); if (only_dynamic_bound) { auto& bound_shape = dest_subshape.is_static() ? src_subshape : dest_subshape; auto& compact_shape = dest_subshape.is_static() ? dest_subshape : src_subshape; CHECK(ShapeUtil::DynamicShapeIsCompatible(compact_shape, bound_shape)) << compact_shape.ToString() << " vs " << bound_shape.ToString(); } else { if (!ShapeUtil::Compatible(dest_subshape, src_subshape)) { return InvalidArgument( "Destination subshape incompatible with source subshape: %s vs %s", ShapeUtil::HumanString(dest_subshape), ShapeUtil::HumanString(src_subshape)); } } return mutable_root_piece().ForEachMutableSubpieceWithStatus( [&](const ShapeIndex& index, Piece* piece) { if (!piece->subshape().IsArray()) { return absl::OkStatus(); } // Determine if this index is in the part of this literal that we want // to copy over from src_literal. bool in_subtree_to_copy = true; for (int i = 0; i < dest_shape_index.size(); ++i) { if (index[i] != dest_shape_index[i]) { in_subtree_to_copy = false; break; } } if (!in_subtree_to_copy) { return absl::OkStatus(); } // Construct the index of the corresponding piece in the source literal. ShapeIndex src_piece_index = src_shape_index; for (int64_t i = dest_shape_index.size(), end = index.size(); i < end; ++i) { src_piece_index.push_back(index[i]); } TF_RETURN_IF_ERROR( piece->CopyFrom(src_literal.piece(src_piece_index), /*only_dynamic_bound=*/only_dynamic_bound)); return absl::OkStatus(); }); } [&](const ShapeIndex& index, Piece* piece) { if (!piece->subshape().IsArray()) { return absl::OkStatus(); } // Determine if this index is in the part of this literal that we want // to copy over from src_literal. bool in_subtree_to_copy = true; for (int i = 0; i < dest_shape_index.size(); ++i) { if (index[i] != dest_shape_index[i]) { in_subtree_to_copy = false; break; } } if (!in_subtree_to_copy) { return absl::OkStatus(); } // Construct the index of the corresponding piece in the source literal. ShapeIndex src_piece_index = src_shape_index; for (int64_t i = dest_shape_index.size(), end = index.size(); i < end; ++i) { src_piece_index.push_back(index[i]); } TF_RETURN_IF_ERROR( piece->CopyFrom(src_literal.piece(src_piece_index), /*only_dynamic_bound=*/only_dynamic_bound)); return absl::OkStatus(); }); absl::Status Literal::MoveFrom(Literal&& src_literal, const ShapeIndex& dest_shape_index) { const Shape& dest_subshape = ShapeUtil::GetSubshape(shape(), dest_shape_index); if (!ShapeUtil::Equal(dest_subshape, src_literal.shape())) { return InvalidArgument( "Destination subshape not equal to source shape: %s vs %s", ShapeUtil::HumanString(dest_subshape), ShapeUtil::HumanString(src_literal.shape())); } src_literal.root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& src_index, Piece* src_piece) { if (!src_piece->subshape().IsArray()) { return; } ShapeIndex dest_index = dest_shape_index; for (int64_t i : src_index) { dest_index.push_back(i); } Piece& dest_piece = piece(dest_index); dest_piece.DeallocateBuffers(); dest_piece.MoveDataFrom(*src_piece); }); src_literal.shape_ = MaybeOwningShapePtr(&NilShape()); src_literal.root_piece_ = Piece(); src_literal.root_piece_.set_subshape(src_literal.shape_.get()); return absl::OkStatus(); } [&](const ShapeIndex& src_index, Piece* src_piece) { if (!src_piece->subshape().IsArray()) { return; } ShapeIndex dest_index = dest_shape_index; for (int64_t i : src_index) { dest_index.push_back(i); } Piece& dest_piece = piece(dest_index); dest_piece.DeallocateBuffers(); dest_piece.MoveDataFrom(*src_piece); }); absl::Status MutableLiteralBase::CopySliceFrom( const LiteralSlice& src_literal, absl::Span<const int64_t> src_base, absl::Span<const int64_t> dest_base, absl::Span<const int64_t> copy_size) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << shape(); TF_RET_CHECK(LayoutUtil::IsDenseArray(src_literal.shape())) << src_literal.shape(); TF_RET_CHECK(ShapeUtil::SameElementType(src_literal.shape(), shape())); TF_RET_CHECK(src_literal.shape().rank() == src_base.size()); TF_RET_CHECK(shape().rank() == dest_base.size()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, [&](auto primitive_type_constant) -> absl::Status { using NativeT = NativeTypeOf<primitive_type_constant>; return CopySliceFromInternal<NativeT>(src_literal, src_base, dest_base, copy_size); }, void MutableLiteralBase::PopulateR1(const tsl::core::Bitmap& values) { CHECK(shape().IsArray()); CHECK_EQ(shape().rank(), 1); CHECK_EQ(element_count(), values.bits()); CHECK_EQ(shape().element_type(), PRED); for (int64_t i = 0; i < static_cast<int64_t>(values.bits()); ++i) { Set({i}, values.get(i)); } } void MutableLiteralBase::PopulateInplaceInternal( absl::FunctionRef<void(void*, absl::Span<const int64_t>, int)> populator, bool parallel) { const Shape& this_shape = shape(); const int64_t rank = this_shape.rank(); DCHECK(LayoutUtil::IsDenseArray(this_shape)); char* const dest_base = static_cast<char*>(untyped_data()); if (rank > 0) { StrideConfig stride_config(this_shape, this_shape, this_shape.dimensions()); const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); const int64_t num_elements = ShapeUtil::ElementsIn(shape()); // If we are rank-1 and we are `parallel`, it is better to use a smaller // `step` than what `StrideConfig` does: stick the entire dimension in the // inner-most loop. if (parallel && this_shape.rank() == 1) { const int64_t thread_count = ShapeUtil::GetForEachIndexParallelThreadCount(); // Let's just divide up the array into small amounts per thread. stride_config.dest_stride = stride_config.minor_loop_size = num_elements > 32 ? std::max<int64_t>(num_elements / thread_count, 1) : num_elements; stride_config.step = {stride_config.minor_loop_size}; } auto init_function = [&](absl::Span<const int64_t> indexes, int thread_id) -> absl::StatusOr<bool> { const int64_t index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), indexes); DimensionVector minor_scan_indexes(rank, 0); std::copy(indexes.begin(), indexes.end(), minor_scan_indexes.begin()); char* dest_ptr = dest_base + index * primitive_size; char* const dest_end = dest_base + // This handles the case where minor_loop_size does not evenly divide // the most minor dimension. std::min(index + stride_config.minor_loop_size, num_elements) * primitive_size; while (dest_ptr < dest_end) { populator(dest_ptr, minor_scan_indexes, thread_id); ++minor_scan_indexes[stride_config.minor_dimension]; dest_ptr += primitive_size; } return true; }; if (parallel) { ShapeUtil::ForEachIndexParallel(this_shape, stride_config.base, stride_config.dimensions, stride_config.step, init_function); } else { ShapeUtil::ForEachIndex( this_shape, stride_config.base, stride_config.dimensions, stride_config.step, [&init_function]( absl::Span<const int64_t> indexes) -> absl::StatusOr<bool> { auto result_ignored = init_function(indexes, /*thread_id=*/-1); return true; }); } } else { // For scalars. populator(dest_base, {}, /*thread_id=*/-1); } } auto init_function = [&](absl::Span<const int64_t> indexes, int thread_id) -> absl::StatusOr<bool> { const int64_t index = IndexUtil::MultidimensionalIndexToLinearIndex(shape(), indexes); DimensionVector minor_scan_indexes(rank, 0); std::copy(indexes.begin(), indexes.end(), minor_scan_indexes.begin()); char* dest_ptr = dest_base + index * primitive_size; char* const dest_end = dest_base + // This handles the case where minor_loop_size does not evenly divide // the most minor dimension. std::min(index + stride_config.minor_loop_size, num_elements) * primitive_size; while (dest_ptr < dest_end) { populator(dest_ptr, minor_scan_indexes, thread_id); ++minor_scan_indexes[stride_config.minor_dimension]; dest_ptr += primitive_size; } return true; }; [&init_function]( absl::Span<const int64_t> indexes) -> absl::StatusOr<bool> { auto result_ignored = init_function(indexes, /*thread_id=*/-1); return true; }); absl::Status MutableLiteralBase::PopulateInplace( absl::FunctionRef<void(void*, absl::Span<const int64_t>)> populator) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); PopulateInplaceInternal( [&](void* dest, absl::Span<const int64_t> indexes, int /*thread_id*/) { return populator(dest, indexes); }, /*parallel=*/false); return absl::OkStatus(); } absl::Status MutableLiteralBase::PopulateInplaceParallel( absl::FunctionRef<void(void*, absl::Span<const int64_t>, int)> populator) { TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); PopulateInplaceInternal(populator, /*parallel=*/element_count() > 32); return absl::OkStatus(); } Literal LiteralBase::Relayout(const Layout& new_layout, const ShapeIndex& shape_index) const { // Create new shape with 'new_layout' set at the given shape index. Shape new_shape = shape(); Shape* subshape = ShapeUtil::GetMutableSubshape(&new_shape, shape_index); TF_CHECK_OK(LayoutUtil::ValidateLayoutForShape(new_layout, *subshape)); *subshape->mutable_layout() = new_layout; // LINT.IfChange // s4 literals are stored in uint8_t/int8_t, therefore element_size_in_bits // must be removed. if (subshape->layout().element_size_in_bits() == 4) { subshape->mutable_layout()->set_element_size_in_bits(0); } // LINT.ThenChange(//tensorflow/compiler/xla/types.h) Literal result(new_shape); TF_CHECK_OK(result.CopyFrom(*this)); return result; } Literal LiteralBase::Relayout(const Shape& shape_with_layout) const { CHECK(ShapeUtil::Compatible(shape_with_layout, shape())) << "Given shape_with_layout " << ShapeUtil::HumanString(shape_with_layout) << " not compatible with literal shape " << ShapeUtil::HumanString(shape()); Literal result = CreateFromShape(shape_with_layout); ShapeUtil::ForEachSubshape( result.shape(), [this, &result](const Shape& subshape, const ShapeIndex& index) { if (subshape.IsArray()) { TF_CHECK_OK(result.CopyFrom(*this, /*dest_shape_index=*/index, /*src_shape_index=*/index)); } }); return result; } [this, &result](const Shape& subshape, const ShapeIndex& index) { if (subshape.IsArray()) { TF_CHECK_OK(result.CopyFrom(*this, /*dest_shape_index=*/index, /*src_shape_index=*/index)); } }); Literal LiteralBase::ToBoundedDynamic(const Shape& bounded_shape) const { CHECK(bounded_shape.is_dynamic()); Literal result(bounded_shape); ShapeUtil::ForEachSubshape( shape(), [&](const Shape& subshape, const ShapeIndex& index) { if (!subshape.IsArray()) { return; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (bounded_shape.is_dynamic_dimension(i)) { result.SetDynamicSize(i, subshape.dimensions(i)); } } }); TF_CHECK_OK(result.CopyFrom(*this, {}, {}, /*only_dynamic_bound=*/true)); return result; } shape(), [&](const Shape& subshape, const ShapeIndex& index) { if (!subshape.IsArray()) { return; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (bounded_shape.is_dynamic_dimension(i)) { result.SetDynamicSize(i, subshape.dimensions(i)); } } }); Literal LiteralBase::ToStatic() const { // Create new shape with 'new_layout' set at the given shape index. Shape new_shape = shape(); ShapeUtil::ForEachMutableSubshape( &new_shape, [this](Shape* subshape, const ShapeIndex& index) { if (!subshape->IsArray()) { return; } for (int64_t i = 0; i < subshape->rank(); ++i) { // GetDynamicSize has a 32-bit return type and may truncate static // dimensions, so make sure to skip. if (!subshape->is_dynamic_dimension(i)) continue; subshape->set_dynamic_dimension(i, false); subshape->set_dimensions(i, GetDynamicSize(i, index)); } }); Literal result(new_shape); TF_CHECK_OK(result.CopyFrom(*this, {}, {}, /*only_dynamic_bound=*/true)); return result; } &new_shape, [this](Shape* subshape, const ShapeIndex& index) { if (!subshape->IsArray()) { return; } for (int64_t i = 0; i < subshape->rank(); ++i) { // GetDynamicSize has a 32-bit return type and may truncate static // dimensions, so make sure to skip. if (!subshape->is_dynamic_dimension(i)) continue; subshape->set_dynamic_dimension(i, false); subshape->set_dimensions(i, GetDynamicSize(i, index)); } }); absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } absl::StatusOr<Literal> BroadcastHelper(const LiteralBase& src, const Shape& src_shape, const Shape& result_shape, absl::Span<const int64_t> dimensions) { for (int64_t i = 0, end = dimensions.size(); i < end; i++) { TF_RET_CHECK(src_shape.dimensions(i) == result_shape.dimensions(dimensions[i])); } TF_RET_CHECK(result_shape.element_type() == src_shape.element_type()); Literal result(result_shape); if (src_shape.is_dynamic()) { for (int64_t i = 0; i < dimensions.size(); ++i) { if (src_shape.is_dynamic_dimension(i)) { // Set any dynamic sizes in the new literal. int64_t dynamic_size = src.GetDynamicSize(i); result.SetDynamicSize(dimensions[i], dynamic_size); } } } // scratch_source_index is temporary storage space for the computed index into // the input literal. We put it here to avoid allocating an std::vector in // every iteration of ShapeUtil::ForEachIndex. int src_shape_dims = src_shape.dimensions_size(); std::vector<int64_t> scratch_source_index(src_shape_dims); // Make the span once outside the ForEachIndex... loop, pointing into // scratch_source_index absl::Span<int64_t> scratch_source_span(scratch_source_index); int64_t* scratch_source_array = scratch_source_span.data(); const char* source_data = static_cast<const char*>(src.untyped_data()); char* dest_data = static_cast<char*>(result.untyped_data()); auto src_minor_to_major = LayoutUtil::MinorToMajor(src_shape); auto result_minor_to_major = LayoutUtil::MinorToMajor(result_shape); ShapeUtil::ForEachIndexNoStatus( result_shape, [&](absl::Span<const int64_t> output_index) { // Compute dest_index int64_t dest_index = IndexUtil::MultidimensionalIndexToLinearIndex( result_shape, result_minor_to_major, output_index); // Compute source_index int64_t source_index; for (int64_t i = 0, end = dimensions.size(); i < end; ++i) { scratch_source_array[i] = output_index[dimensions[i]]; } if (src_shape_dims == 1) { // Fast path for this case source_index = scratch_source_array[0]; DCHECK_EQ(source_index, IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span)); } else { source_index = IndexUtil::MultidimensionalIndexToLinearIndex( src_shape, src_minor_to_major, scratch_source_span); } // Move one element from source_index in source to dest_index in dest memcpy(dest_data + PRIMITIVE_SIZE * dest_index, source_data + PRIMITIVE_SIZE * source_index, PRIMITIVE_SIZE); return true; }); return std::move(result); } result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { result_shape, [&](absl::Span<const int64_t> output_index) { absl::StatusOr<Literal> LiteralBase::Broadcast( const Shape& result_shape, absl::Span<const int64_t> dimensions) const { const LiteralBase& src = *this; const Shape& src_shape = shape(); if (!src_shape.IsArray()) { return InvalidArgument("Broadcast only supports arrays."); } const int64_t primitive_size = ShapeUtil::ByteSizeOfPrimitiveType(src_shape.element_type()); switch (primitive_size) { case 0: return BroadcastHelper<0>(src, src_shape, result_shape, dimensions); case 1: return BroadcastHelper<1>(src, src_shape, result_shape, dimensions); case 2: return BroadcastHelper<2>(src, src_shape, result_shape, dimensions); case 4: return BroadcastHelper<4>(src, src_shape, result_shape, dimensions); case 8: return BroadcastHelper<8>(src, src_shape, result_shape, dimensions); case 16: return BroadcastHelper<16>(src, src_shape, result_shape, dimensions); default: LOG(FATAL) << "Unhandled primitive size " << primitive_size; return InvalidArgument("Unhandled primitive size"); break; } } absl::StatusOr<Literal> LiteralBase::Reshape( absl::Span<const int64_t> dimensions) const { if (!LayoutUtil::IsDenseArray(shape())) { return InvalidArgument("Reshape is only supported for dense arrays."); } if (shape().is_dynamic()) { // TODO(b/243182930): We should consider supporting dynamic reshape. return Unimplemented("Dynamic reshape is not implemented."); } Literal output; if (!LayoutUtil::IsMonotonicWithDim0Major(shape().layout())) { output = Relayout(LayoutUtil::GetDefaultLayoutForRank(shape().rank())); } else { output = Clone(); } // Because the layout is monotonic, we can simply reuse the same sequence of // values without changing their order. *output.mutable_shape_do_not_use() = ShapeUtil::MakeShape(shape().element_type(), dimensions); int64_t elements_before = ShapeUtil::ElementsIn(shape()); int64_t elements_after = ShapeUtil::ElementsIn(output.shape()); if (elements_before != elements_after) { return InvalidArgument( "Shapes before and after Literal::Reshape have different numbers " "of elements: %s vs %s.", ShapeUtil::HumanString(shape()), ShapeUtil::HumanString(output.shape())); } return std::move(output); } Literal LiteralBase::Transpose(absl::Span<const int64_t> permutation) const { CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); CHECK(shape().rank() == permutation.size() && IsPermutation(permutation)) << "Given permutation is not a permutation of dimension numbers"; // To transpose the array, we just permute the dimensions and layout, and // do a straight memory copy of the raw data set. // This is considerably faster than iterating over every array element using // the EachCell<>() and Set<>() APIs. Shape permuted_shape = ShapeUtil::PermuteDimensions(permutation, shape()); // Replace the layout with one affine to this shape, such that a // transpose operation can be performed by leaving the flat values // representation intact. // For example, consider the shape F32[11,8]{1,0} under a {1,0} permutation. // The shape with affine layout resulting from that operation will be // F32[8,11]{0,1}, since it leaves the original most minor (the 8 sized), the // most minor. // // Essentially, given MinMaj(Di) the position of the Di dimension within the // minor to major vector, and given T(Di) the index that the original Di // dimension has within the transposed array, a layout is affine if // MinMaj(Di) == TMinMaj(T(Di)), with TMinMaj() being the minor to major // vector of the affine layout. std::vector<int64_t> inverse_permutation = InversePermutation(permutation); CHECK(LayoutUtil::IsDenseArray(permuted_shape)); Layout* layout = permuted_shape.mutable_layout(); layout->clear_minor_to_major(); for (auto index : LayoutUtil::MinorToMajor(shape())) { layout->add_minor_to_major(inverse_permutation[index]); } Literal new_literal(permuted_shape); if (shape().is_dynamic()) { for (int64_t i = 0; i < shape().rank(); i++) { if (shape().is_dynamic_dimension(i)) { // Set the dynamic size of any dynamic dimension in the transposed // literal. new_literal.SetDynamicSize(inverse_permutation[i], GetDynamicSize(i)); } } } DCHECK_EQ(ShapeUtil::ByteSizeOf(new_literal.shape()), ShapeUtil::ByteSizeOf(shape())); std::memcpy(new_literal.untyped_data(), untyped_data(), size_bytes()); return new_literal; } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } void SliceInternal(const LiteralBase& src_literal, absl::Span<const int64_t> start_indices, Literal& result_literal) { const Shape& result_shape = result_literal.shape(); DimensionVector new_indices(result_shape.rank()); TF_CHECK_OK( result_literal.Populate<NativeT>([&](absl::Span<const int64_t> indices) { for (int64_t i = 0; i < result_shape.rank(); ++i) { new_indices[i] = indices[i] + start_indices[i]; } return src_literal.Get<NativeT>(new_indices); })); for (int64_t dnum = 0; dnum < src_literal.shape().rank(); ++dnum) { if (src_literal.shape().is_dynamic_dimension(dnum)) { int64_t dynamic_size = src_literal.GetDynamicSize(dnum) - start_indices[dnum]; CHECK_GE(dynamic_size, 0) << src_literal.GetDynamicSize(dnum); dynamic_size = std::min(dynamic_size, result_shape.dimensions(dnum)); result_literal.SetDynamicSize(dnum, dynamic_size); } } } TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( TF_CHECK_OK( Literal LiteralBase::Slice(absl::Span<const int64_t> start_indices, absl::Span<const int64_t> limit_indices) const { CHECK(shape().IsArray()) << "tuple is not supported for slice"; DimensionVector result_dimensions; for (int64_t dnum = 0; dnum < shape().rank(); ++dnum) { CHECK_GE(start_indices[dnum], 0); CHECK_LE(limit_indices[dnum], shape().dimensions(dnum)) << "dnum = " << dnum; int64_t dimension = limit_indices[dnum] - start_indices[dnum]; CHECK_GE(dimension, 0) << "dnum = " << dnum; result_dimensions.push_back(dimension); } auto result_shape = ShapeUtil::MakeShapeWithDenseLayout( shape().element_type(), result_dimensions, LayoutUtil::MinorToMajor(shape())); ShapeUtil::CopyDynamicDimensions(&result_shape, shape()); Literal result_literal(result_shape); primitive_util::ArrayTypeSwitch<void>( [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; return SliceInternal<NativeT>(*this, start_indices, result_literal); }, result_shape.element_type()); return result_literal; } Literal LiteralBase::Clone() const { Literal result(shape()); TF_CHECK_OK(result.CopyFrom(*this)); return result; } std::unique_ptr<Literal> LiteralBase::CloneToUnique() const { auto result = std::make_unique<Literal>(shape()); TF_CHECK_OK(result->CopyFrom(*this)); return result; } bool LiteralBase::IsDetermined(const ShapeIndex& shape_index) const { return piece(shape_index).IsDetermined(); } bool LiteralBase::IsKnown(const ShapeIndex& shape_index) const { return piece(shape_index).IsKnown(); } std::string LiteralBase::GetAsString(absl::Span<const int64_t> multi_index, const ShapeIndex& shape_index) const { const Shape& subshape = ShapeUtil::GetSubshape(shape(), shape_index); CHECK(LayoutUtil::IsDenseArray(subshape)); return primitive_util::ArrayTypeSwitch<std::string>( [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, subshape.element_type()); } [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, [&](auto primitive_type_constant) -> std::string { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsIntegralType(primitive_type_constant)) { return StrCat(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return RoundTripFpToString(Get<NativeT>(multi_index, shape_index)); } if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { NativeT c = Get<NativeT>(multi_index, shape_index); return StrCat("(", RoundTripFpToString(c.real()), ", ", RoundTripFpToString(c.imag()), ")"); } if constexpr (primitive_type_constant == PRED) { return Get<bool>(multi_index, shape_index) ? "true" : "false"; } LOG(FATAL) << PrimitiveType_Name(subshape.element_type()); }, std::optional<int64_t> LiteralBase::GetIntegralAsS64( absl::Span<const int64_t> multi_index) const { CHECK(LayoutUtil::IsDenseArray(shape())); return primitive_util::PrimitiveTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(multi_index); } return std::nullopt; }, std::optional<double> LiteralBase::GetAsDouble( absl::Span<const int64_t> multi_index) const { const Shape& s = shape(); CHECK(LayoutUtil::IsDenseArray(s)); return primitive_util::PrimitiveTypeSwitch<std::optional<double>>( [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, s.element_type()); } [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<double> { if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; return static_cast<double>(Get<NativeT>(multi_index)); } return std::nullopt; }, std::optional<double> LiteralBase::GetSumAsDouble( absl::Span<const int64_t> linear_indices) const { const Shape& s = shape(); CHECK(LayoutUtil::IsDenseArray(s)); if (!primitive_util::IsFloatingPointType(s.element_type())) { return std::nullopt; } return primitive_util::FloatingPointTypeSwitch<double>( [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, s.element_type()); } [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, [&](auto primitive_type_constant) -> double { using NativeT = NativeTypeOf<primitive_type_constant>; double sum = 0.0; auto d = root_piece().data<NativeT>(); for (const int64_t idx : linear_indices) { sum += static_cast<double>(d[idx]); } return sum; }, std::optional<complex128> LiteralBase::GetAsComplex128( absl::Span<const int64_t> multi_index) const { return primitive_util::PrimitiveTypeSwitch<std::optional<complex128>>( [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, [&](auto primitive_type_constant) -> std::optional<complex128> { if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { using NativeT = NativeTypeOf<primitive_type_constant>; if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { return {Get<NativeT>(multi_index)}; } if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } if constexpr (primitive_util::IsIntegralType( primitive_type_constant) && primitive_type_constant != S64 && primitive_type_constant != U64) { return {{static_cast<double>(Get<NativeT>(multi_index)), 0}}; } } return std::nullopt; }, absl::Status MutableLiteralBase::SetIntegralAsS64( absl::Span<const int64_t> multi_index, int64_t value) { CHECK(LayoutUtil::IsDenseArray(shape())); return primitive_util::PrimitiveTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsIntegralType(primitive_type_constant) || primitive_type_constant == PRED) { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); return absl::OkStatus(); } return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); }, absl::Status MutableLiteralBase::SetFromDouble( absl::Span<const int64_t> multi_index, double value) { CHECK(LayoutUtil::IsDenseArray(shape())); if (!primitive_util::IsFloatingPointType(shape().element_type())) { return FailedPrecondition("Array element type is not integral: %s", PrimitiveType_Name(shape().element_type())); } primitive_util::FloatingPointTypeSwitch<void>( [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, shape().element_type()); return absl::OkStatus(); } [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, [&](auto primitive_type_constant) -> void { using NativeT = NativeTypeOf<primitive_type_constant>; Set<NativeT>(multi_index, static_cast<NativeT>(value)); }, void PrintShape(bool print_layout, const Shape& shape, Printer* printer) { if (print_layout) { ShapeUtil::PrintHumanStringWithLayout(printer, shape); } else { ShapeUtil::PrintHumanString(printer, shape); } } void TuplePrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); printer->Append(oneline ? "( " : "(\n"); for (int i = 0; i < ShapeUtil::TupleElementCount(subshape); ++i) { ShapeIndex element_index = shape_index; element_index.push_back(i); if (i > 0) printer->Append(oneline ? ", " : ",\n"); PrintHelper(literal, element_index, print_shape, print_layout, oneline, printer); } printer->Append(oneline ? " )" : "\n)"); } void DenseArrayPrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); int64_t rank = subshape.rank(); const absl::string_view linebreak = oneline ? " " : "\n"; std::function<void(absl::Span<const int64_t> dimensions, std::vector<int64_t>*)> print_recursive = [&](absl::Span<const int64_t> dimensions, std::vector<int64_t>* accum_indices) { // dimensions.size() decreases by 1 at each recursive call, // and accum_indices->size() increases by 1. // Their sum is equal to the rank of the tensor. CHECK_EQ(rank, dimensions.size() + accum_indices->size()); auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; if (dimensions.empty()) { // Display predicates as 0s and 1s so that the string is more dense. std::string elem; if (subshape.element_type() == PRED && rank > 0) { elem = literal.Get<bool>(*accum_indices, shape_index) ? "1" : "0"; } else { elem = literal.GetAsString(*accum_indices, shape_index); } printer->Append(elem); } else { printer->Append(brace_to_string("{")); for (int i = 0; i < dimensions[0]; ++i) { accum_indices->push_back(i); print_recursive(dimensions.subspan(1), accum_indices); accum_indices->pop_back(); if (i < dimensions[0] - 1) { printer->Append(","); printer->Append(dimensions.size() > 1 ? linebreak : " "); } } printer->Append(brace_to_string("}")); } }; if (print_shape) { PrintShape(print_layout, subshape, printer); if (subshape.is_dynamic()) { printer->Append("("); for (int64_t i = 0; i < subshape.dimensions_size(); ++i) { printer->Append(literal.GetDynamicSize(i, shape_index)); if (i < subshape.dimensions_size() - 1) { printer->Append(","); } } printer->Append(")"); } printer->Append(" "); } std::vector<int64_t> indices = {}; std::vector<int64_t> dimensions; dimensions.reserve(subshape.rank()); for (int64_t i = 0; i < subshape.rank(); ++i) { dimensions.push_back(literal.GetDynamicSize(i, shape_index)); } print_recursive(dimensions, &indices); } print_recursive = [&](absl::Span<const int64_t> dimensions, std::vector<int64_t>* accum_indices) { // dimensions.size() decreases by 1 at each recursive call, // and accum_indices->size() increases by 1. // Their sum is equal to the rank of the tensor. CHECK_EQ(rank, dimensions.size() + accum_indices->size()); auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; if (dimensions.empty()) { // Display predicates as 0s and 1s so that the string is more dense. std::string elem; if (subshape.element_type() == PRED && rank > 0) { elem = literal.Get<bool>(*accum_indices, shape_index) ? "1" : "0"; } else { elem = literal.GetAsString(*accum_indices, shape_index); } printer->Append(elem); } else { printer->Append(brace_to_string("{")); for (int i = 0; i < dimensions[0]; ++i) { accum_indices->push_back(i); print_recursive(dimensions.subspan(1), accum_indices); accum_indices->pop_back(); if (i < dimensions[0] - 1) { printer->Append(","); printer->Append(dimensions.size() > 1 ? linebreak : " "); } } printer->Append(brace_to_string("}")); } }; auto brace_to_string = [&](std::string brace) -> std::string { // Handle 1D tensor if (rank == 1) { return brace; } // Handle the innermost tensor of a 2D+ tensor. if (dimensions.size() == 1 && brace == "{") { return StrCat(oneline ? "" : " ", brace, dimensions[0] <= 1 ? "" : " "); } if (dimensions.size() == 1 && brace == "}") { return StrCat(dimensions[0] <= 1 ? "" : " ", brace); } // Handle the non-innermost tensors of a 2D+ tensor. if (brace == "{") { const int64_t accum_indices_size = accum_indices->size(); if (rank > 3 && !accum_indices->empty() && accum_indices_size < rank) { int index = accum_indices->size() - 1; int value = accum_indices->back(); int size = dimensions.front(); return StrCat(brace, " /*i", index, "=", value, "*/", size > 0 ? linebreak : ""); } return StrCat(brace, linebreak); } return StrCat(linebreak, brace); }; void PrintHelper(const LiteralBase& literal, const ShapeIndex& shape_index, bool print_shape, bool print_layout, bool oneline, Printer* printer) { const Shape& subshape = ShapeUtil::GetSubshape(literal.shape(), shape_index); CHECK(LayoutUtil::HasLayout(literal.shape())); CHECK(LayoutUtil::HasLayout(subshape)); if (subshape.IsTuple()) { TuplePrintHelper(literal, shape_index, print_shape, print_layout, oneline, printer); } else if (subshape.IsToken()) { printer->Append("token"); } else { CHECK(LayoutUtil::IsDenseArray(subshape)); if (literal.IsKnown(shape_index)) { DenseArrayPrintHelper(literal, shape_index, print_shape, print_layout, oneline, printer); } else { PrintShape(print_layout, subshape, printer); printer->Append(" "); if (literal.IsDetermined(shape_index)) { printer->Append("unknown"); } else { printer->Append("undetermined"); } } } } void LiteralBase::Print(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/false, /*oneline=*/false, printer); } void LiteralBase::PrintOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/false, /*oneline=*/true, printer); } void LiteralBase::PrintWithoutShape(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/false, /*print_layout=*/false, /*oneline=*/false, printer); } void LiteralBase::PrintWithoutShapeOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/false, /*print_layout=*/false, /*oneline=*/true, printer); } void LiteralBase::PrintWithLayout(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/true, /*oneline=*/false, printer); } void LiteralBase::PrintWithLayoutOneline(Printer* printer) const { CHECK(LayoutUtil::HasLayout(this->shape())); PrintHelper(*this, {}, /*print_shape=*/true, /*print_layout=*/true, /*oneline=*/true, printer); } std::string LiteralBase::ToString() const { StringPrinter printer; Print(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringOneline() const { StringPrinter printer; PrintOneline(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithoutShape() const { StringPrinter printer; PrintWithoutShape(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithoutShapeOneline() const { StringPrinter printer; PrintWithoutShapeOneline(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithLayout() const { StringPrinter printer; PrintWithLayout(&printer); return std::move(printer).ToString(); } std::string LiteralBase::ToStringWithLayoutOneline() const { StringPrinter printer; PrintWithLayoutOneline(&printer); return std::move(printer).ToString(); } void LiteralBase::EachCellAsString( absl::FunctionRef<void(absl::Span<const int64_t> indices, const std::string& value)> per_cell) const { if (ShapeUtil::IsZeroElementArray(shape())) { return; } auto indices = IndexUtil::LinearIndexToMultidimensionalIndex( shape(), /*linear_index=*/0); do { per_cell(indices, GetAsString(indices)); } while (IndexUtil::BumpIndices(shape(), absl::MakeSpan(indices))); } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } void ConvertBetweenNativeTypes(absl::Span<const NativeSrcT> src_data, void* dst_base) { static_assert(!std::is_same_v<NativeSrcT, NativeDestT>); auto converter = [](NativeSrcT src) -> NativeDestT { // C++ [conv.bool]p1: // A prvalue of arithmetic [...] type can be converted to a prvalue of // type bool. A zero value [...] is converted to false; any other value is // converted to true. // C++ [conv.fpint]p1: // [...] The behavior is undefined if the truncated value cannot be // represented in the destination type. // // Using static_cast to convert a float to an integral type other than bool // may be undefined if the value's magnitude is too large or it is a NaN. // Let's choose saturating arithmetic as it captures the spirit of infinity // and arbitrarily map NaN to zero. if constexpr (!std::is_same_v<NativeDestT, bool> && !std::numeric_limits<NativeSrcT>::is_integer && std::numeric_limits<NativeDestT>::is_integer) { if (src != src) { return NativeDestT{0}; } if (src >= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::max())) { return std::numeric_limits<NativeDestT>::max(); } if (src <= static_cast<NativeSrcT>(std::numeric_limits<NativeDestT>::lowest())) { return std::numeric_limits<NativeDestT>::lowest(); } } return static_cast<NativeDestT>(src); }; NativeDestT* dest_data = static_cast<NativeDestT*>(dst_base); for (const NativeSrcT& src : src_data) { *(dest_data++) = converter(src); } } auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { auto converter = [](NativeSrcT src) -> NativeDestT { absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } absl::Status ConvertIfDestTypeMatches(const LiteralBase& src_literal, MutableLiteralBase& dst_literal) { DCHECK(dst_literal.shape().IsArray()); using NativeSrcT = NativeTypeOf<kSrcType>; // Pass raw data Span/pointers to called template methods to avoid duplicating // the Literal method calls to many time which hurts code size. auto src_data = src_literal.data<NativeSrcT>(); void* dst_base = dst_literal.untyped_data(); DCHECK_EQ(src_data.size(), dst_literal.element_count()); return primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { if constexpr (primitive_util::IsComplexType(kSrcType) && !primitive_util::IsComplexType(primitive_type_constant)) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(kSrcType), PrimitiveType_Name(primitive_type_constant())); } else if constexpr (kSrcType != primitive_type_constant) { using NativeDestT = NativeTypeOf<primitive_type_constant>; ConvertBetweenNativeTypes<NativeSrcT, NativeDestT>(src_data, dst_base); } return absl::OkStatus(); }, dst_literal.shape().element_type()); } [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { [&](auto primitive_type_constant) -> absl::Status { absl::StatusOr<Literal> ConvertSwitch(const LiteralBase& literal, PrimitiveType primitive_dest_type) { TF_RET_CHECK(LayoutUtil::IsDenseArray(literal.shape())); if (literal.shape().element_type() == primitive_dest_type) { return literal.Clone(); } // Source Array type requirement is ensured by IsDenseArray before. if (!primitive_util::IsArrayType(primitive_dest_type) || !primitive_util::IsArrayType(literal.shape().element_type())) { return Unimplemented("%s from type %s to type %s is not implemented.", "Converting", PrimitiveType_Name(literal.shape().element_type()), PrimitiveType_Name(primitive_dest_type)); } // At this point, we know both src & dst are array types, while src is not // complex type, so we can allocate the result literal here to avoid // duplicating it N^2 times in the conversion implementation. Literal result( ShapeUtil::ChangeElementType(literal.shape(), primitive_dest_type)); TF_RETURN_IF_ERROR(primitive_util::ArrayTypeSwitch<absl::Status>( [&](auto primitive_type_constant) -> absl::Status { return ConvertIfDestTypeMatches<primitive_type_constant>(literal, result); }, literal.shape().element_type())); return result; } absl::StatusOr<Literal> LiteralBase::Convert( PrimitiveType primitive_dest_type) const { return ConvertSwitch(*this, primitive_dest_type); } absl::StatusOr<Literal> LiteralBase::BitcastConvert( const Shape& dest_shape) const { if (ShapeUtil::ByteSizeOf(dest_shape) != ShapeUtil::ByteSizeOf(shape())) { return InvalidArgument( "Can not bitcast-convert from shape %s to a shape of different size %s", shape().ToString(), dest_shape.ToString()); } if (dest_shape.IsTuple() || shape().IsTuple()) { return InvalidArgument( "bitcast-convert is not valid for tuple shapes %s->%s", shape().ToString(), dest_shape.ToString()); } if (shape().is_dynamic() || dest_shape.is_dynamic()) { return InvalidArgument( "bitcast-convert is not valid for dynamic shape %s->%s", shape().ToString(), dest_shape.ToString()); } Literal out(dest_shape); std::memcpy(out.root_piece_.buffer(), root_piece().buffer(), root_piece().size_bytes_dense()); // Perform the reshape on little endian encoding even on big endian machines. if constexpr (!kLittleEndian) { // Swap byte ordering as per the input data type. size_t input_elem_size = ShapeUtil::ByteSizeOfPrimitiveType(shape().element_type()); TF_RETURN_IF_ERROR(tsl::ByteSwapArray( const_cast<char*>(out.root_piece().buffer()), input_elem_size, out.root_piece().size_bytes_dense() / input_elem_size)); // Swap byte ordering as per the output data type. size_t output_elem_size = ShapeUtil::ByteSizeOfPrimitiveType(dest_shape.element_type()); TF_RETURN_IF_ERROR(tsl::ByteSwapArray( const_cast<char*>(out.root_piece().buffer()), output_elem_size, out.root_piece().size_bytes_dense() / output_elem_size)); } return out; } absl::StatusOr<Literal> LiteralBase::ConvertToShape( const Shape& dest_shape) const { if (!dest_shape.IsTuple()) { return Convert(dest_shape.element_type()); } std::vector<Literal> elements; const auto tuple_element_count = ShapeUtil::TupleElementCount(shape()); elements.reserve(tuple_element_count); for (int i = 0; i < tuple_element_count; ++i) { auto element = LiteralSlice(*this, {i}); TF_ASSIGN_OR_RETURN( auto new_element, element.ConvertToShape(ShapeUtil::GetSubshape(dest_shape, {i}))); elements.push_back(std::move(new_element)); } return MutableLiteralBase::MoveIntoTuple(absl::MakeSpan(elements)); } /* static */ Literal MutableLiteralBase::MoveIntoTuple( absl::Span<Literal> elements) { std::vector<const Shape*> element_shapes; element_shapes.reserve(elements.size()); for (const Literal& element : elements) { element_shapes.push_back(&element.shape()); } Literal literal(ShapeUtil::MakeTupleShapeWithPtrs(element_shapes), /*allocate_arrays=*/false); for (int i = 0, end = elements.size(); i < end; ++i) { TF_CHECK_OK( literal.MoveFrom(std::move(elements[i]), /*dest_shape_index=*/{i})); } return literal; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualElementsInternal( const LiteralBase::Piece& other, std::vector<int64_t>* multi_index) const { if (multi_index->size() == subshape().rank()) { return (Get<NativeT>(*multi_index) == other.Get<NativeT>(*multi_index)); } for (int64_t i = 0; i < GetDynamicSize(multi_index->size()); ++i) { multi_index->push_back(i); if (!EqualElementsInternal<NativeT>(other, multi_index)) { return false; } multi_index->pop_back(); } return true; } bool LiteralBase::Piece::EqualDynamicSize( const LiteralBase::Piece& other) const { DCHECK(ShapeUtil::Compatible(subshape(), other.subshape())); if (subshape().is_static()) { return true; } for (int64_t i = 0; i < subshape().rank(); ++i) { if (GetDynamicSize(i) != other.GetDynamicSize(i)) { return false; } } return true; } bool LiteralBase::Piece::EqualElements(const LiteralBase::Piece& other) const { if (subshape().is_static() && ShapeUtil::Equal(subshape(), other.subshape()) && subshape().IsArray()) { CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(size_bytes_dense(), other.size_bytes_dense()); if (primitive_util::IsSubByteNonPredType(subshape().element_type())) { CHECK(!primitive_util::IsFloatingPointType(subshape().element_type())); auto one_array = buffer(); auto two_array = other.buffer(); const int bits_per_element = primitive_util::BitWidth(subshape().element_type()); const uint8_t mask = LsbMask<uint8_t>(bits_per_element); for (int64_t i = 0; i < size_bytes_dense(); ++i) { if ((one_array[i] & mask) != (two_array[i] & mask)) return false; } return true; } return memcmp(buffer(), other.buffer(), size_bytes_dense()) == 0; } std::vector<int64_t> multi_index; return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeSrcT = NativeTypeOf<primitive_type_constant>; return EqualElementsInternal<NativeSrcT>(other, &multi_index); }, subshape().element_type()); } bool LiteralBase::Equal(const LiteralBase& other, bool layout_sensitive) const { // Checking the structure of tuple literals. Checks for dense arrays are // performed below. if (!ShapeUtil::EqualStructure(shape(), other.shape())) { return false; } return root_piece().ForEachSubpieceWithBool([&](const ShapeIndex& index, const Piece& piece) { const Piece& other_piece = other.piece(index); const Shape& subshape = piece.subshape(); const Shape& other_subshape = other_piece.subshape(); if (subshape.element_type() != other_subshape.element_type()) { return false; } if (!piece.subshape().IsArray()) { return true; } if (subshape.rank() != other_subshape.rank()) { return false; } if (layout_sensitive && (subshape.layout() != other_subshape.layout())) { return false; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (piece.GetDynamicSize(i) != other_piece.GetDynamicSize(i)) { return false; } } if (!piece.EqualElements(other_piece)) { return false; } return true; }); } return root_piece().ForEachSubpieceWithBool([&](const ShapeIndex& index, const Piece& piece) { const Piece& other_piece = other.piece(index); const Shape& subshape = piece.subshape(); const Shape& other_subshape = other_piece.subshape(); if (subshape.element_type() != other_subshape.element_type()) { return false; } if (!piece.subshape().IsArray()) { return true; } if (subshape.rank() != other_subshape.rank()) { return false; } if (layout_sensitive && (subshape.layout() != other_subshape.layout())) { return false; } for (int64_t i = 0; i < subshape.rank(); ++i) { if (piece.GetDynamicSize(i) != other_piece.GetDynamicSize(i)) { return false; } } if (!piece.EqualElements(other_piece)) { return false; } return true; }); static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(NativeT a, NativeT b) { if constexpr (std::numeric_limits<NativeT>::has_quiet_NaN || std::numeric_limits<NativeT>::has_signaling_NaN) { if (Eigen::numext::isnan(a) && Eigen::numext::isnan(b)) { return true; } } return a == b; } static bool EqualIncludingNan(std::complex<T> a, std::complex<T> b) { return EqualIncludingNan(a.real(), b.real()) && EqualIncludingNan(a.imag(), b.imag()); } static bool EqualIncludingNan(std::complex<T> a, std::complex<T> b) { return EqualIncludingNan(a.real(), b.real()) && EqualIncludingNan(a.imag(), b.imag()); } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } static bool AllElementsEqualValue(absl::Span<const NativeT> data, NativeT value) { for (int64_t i = 0; i < data.size(); ++i) { if (!EqualIncludingNan(data[i], value)) { return false; } } return true; } bool Literal::Piece::IsAll(const Literal& scalar) const { CHECK(ShapeUtil::IsScalar(scalar.shape())) << scalar.shape().ToString(); if (!subshape().IsArray()) { return false; } CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(subshape().element_type(), scalar.shape().element_type()); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, subshape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return AllElementsEqualValue(this->data<NativeT>(), scalar.GetFirstElement<NativeT>()); }, int64_t Literal::Piece::CountAll(const Literal& scalar) const { CHECK(ShapeUtil::IsScalar(scalar.shape())) << scalar.shape().ToString(); if (!subshape().IsArray()) { return 0; } CHECK(LayoutUtil::IsDenseArray(subshape())) << __func__ << " is only supported for dense arrays: " << subshape(); CHECK_EQ(subshape().element_type(), scalar.shape().element_type()); return primitive_util::ArrayTypeSwitch<int64_t>( [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, subshape().element_type()); } [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, [&](auto primitive_type_constant) -> int64_t { using NativeT = NativeTypeOf<primitive_type_constant>; return absl::c_count_if( this->data<NativeT>(), [&](NativeT elem) -> bool { return EqualIncludingNan(elem, scalar.GetFirstElement<NativeT>()); }); }, this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { this->data<NativeT>(), [&](NativeT elem) -> bool { bool LiteralBase::IsAll(const Literal& scalar) const { return root_piece().IsAll(scalar); } bool LiteralBase::IsAll(int8_t value) const { if (!shape().IsArray()) { return false; } PrimitiveType ty = shape().element_type(); if (primitive_util::IsFloatingPointType(ty)) { return IsAllFloatImpl(value, /*round_value=*/false); } if (primitive_util::IsUnsignedIntegralType(ty) && value < 0) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; NativeT converted(value); if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (!Eigen::numext::isfinite(converted)) { return false; } } if constexpr (!primitive_util::IsComplexType(primitive_type_constant)) { if (static_cast<int8_t>(converted) != value) { return false; } } scalar.Set<NativeT>({}, converted); return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllFloat(float value) const { return IsAllFloatImpl(value, /*round_value=*/true); } bool LiteralBase::IsAllFloatImpl(float value, bool round_value) const { PrimitiveType ty = shape().element_type(); if (!primitive_util::IsFloatingPointType(ty)) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::FloatingPointTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); if (!round_value && scalar.GetAsDouble({}) != value) { return false; } return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllComplex(complex64 value) const { PrimitiveType ty = shape().element_type(); if (!primitive_util::IsComplexType(ty)) { return false; } Literal scalar(ShapeUtil::MakeScalarShape(ty)); return primitive_util::ComplexTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, ty); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; scalar.Set<NativeT>({}, static_cast<NativeT>(value)); return root_piece().IsAll(scalar); }, bool LiteralBase::IsAllFirst() const { if (!shape().IsArray()) { return false; } // Empty shapes are not all the first element since there is no first element. if (ShapeUtil::IsZeroElementArray(shape())) { return false; } absl::InlinedVector<int64_t, 4> start_indices(/*n=*/shape().rank(), 0); absl::InlinedVector<int64_t, 4> end_indices(/*n=*/shape().rank(), 1); Literal first = Slice(start_indices, end_indices); return IsAll(first.Reshape({}).value()); } bool LiteralBase::IsR1Iota() const { if (!shape().IsArray()) { return false; } CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); if (shape().rank() != 1) { return false; } return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, shape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; const int64_t elements = ShapeUtil::ElementsIn(shape()); for (int64_t idx = 0; idx < elements; ++idx) { if constexpr (primitive_util::IsIntegralType( primitive_type_constant)) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx) { return false; } } else if constexpr (primitive_util::IsFloatingPointType( primitive_type_constant)) { if (Get<NativeT>({idx}) != static_cast<NativeT>(idx)) { return false; } } else if constexpr (primitive_util::IsComplexType( primitive_type_constant)) { if (Get<NativeT>({idx}) != NativeT(idx, 0.0f)) { return false; } } else { // pred is not iota. return false; } } return true; }, std::optional<int64_t> LiteralBase::IsR1StridedIota() const { if (!shape().IsArray() || shape().rank() != 1) { return std::nullopt; } CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); const int64_t elements = ShapeUtil::ElementsIn(shape()); const PrimitiveType type = shape().element_type(); if (elements <= 1 || !primitive_util::IsIntegralType(type)) { return std::nullopt; } return primitive_util::IntegralTypeSwitch<std::optional<int64_t>>( [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, shape().element_type()); } [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, [&](auto primitive_type_constant) -> std::optional<int64_t> { using NativeT = NativeTypeOf<primitive_type_constant>; // Infer the stride as the second element (since first element is // supposed to be zero). const int64_t stride = static_cast<int64_t>(Get<NativeT>({1})); if (stride == 0) { return std::nullopt; } for (int64_t idx = 0; idx < elements; ++idx) { if (static_cast<int64_t>(Get<NativeT>({idx})) != idx * stride) { return std::nullopt; } } return stride; }, bool LiteralBase::IsZero(absl::Span<const int64_t> indices) const { CHECK(LayoutUtil::IsDenseArray(shape())) << __func__ << " is only supported for dense arrays: " << shape(); return primitive_util::ArrayTypeSwitch<bool>( [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, shape().element_type()); } [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, [&](auto primitive_type_constant) -> bool { using NativeT = NativeTypeOf<primitive_type_constant>; return Get<NativeT>(indices) == NativeT{0}; }, void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void CopyToRepeatedField(RepeatedFieldT* dest, const absl::Span<const NativeT> src) { *dest = RepeatedFieldT(src.begin(), src.end()); } void LiteralBase::Piece::set_array_value_state(ArrayValueState state) { array_value_state_ = state; } LiteralBase::ArrayValueState LiteralBase::Piece::get_array_value_state() const { return array_value_state_; } void LiteralBase::Piece::WriteToProto(LiteralProto* proto) const { *proto->mutable_shape() = subshape().ToProto(); switch (subshape().element_type()) { case PRED: CopyToRepeatedField(proto->mutable_preds(), data<bool>()); break; case U2: *proto->mutable_u2s() = std::string( reinterpret_cast<const char*>(data<u2>().data()), size_bytes_dense()); break; case U4: *proto->mutable_u4s() = std::string( reinterpret_cast<const char*>(data<u4>().data()), size_bytes_dense()); break; case U8: proto->set_u8s(static_cast<const unsigned char*>(data<uint8_t>().data()), element_count()); break; case U16: *proto->mutable_u16s() = std::string(reinterpret_cast<const char*>(data<uint16_t>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_u16s()); } break; case U32: CopyToRepeatedField(proto->mutable_u32s(), data<uint32_t>()); break; case U64: CopyToRepeatedField(proto->mutable_u64s(), data<uint64_t>()); break; case S2: *proto->mutable_s2s() = std::string( reinterpret_cast<const char*>(data<s2>().data()), size_bytes_dense()); break; case S4: *proto->mutable_s4s() = std::string( reinterpret_cast<const char*>(data<s4>().data()), size_bytes_dense()); break; case S8: proto->set_s8s(static_cast<const signed char*>(data<int8_t>().data()), element_count()); break; case S16: *proto->mutable_s16s() = std::string(reinterpret_cast<const char*>(data<int16_t>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_s16s()); } break; case S32: CopyToRepeatedField(proto->mutable_s32s(), data<int32_t>()); break; case S64: CopyToRepeatedField(proto->mutable_s64s(), data<int64_t>()); break; case F8E5M2: *proto->mutable_f8e5m2s() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e5m2>().data()), size_bytes_dense()); break; case F8E4M3FN: *proto->mutable_f8e4m3fns() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3fn>().data()), size_bytes_dense()); break; case F8E4M3B11FNUZ: *proto->mutable_f8e4m3b11fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3b11fnuz>().data()), size_bytes_dense()); break; case F8E5M2FNUZ: *proto->mutable_f8e5m2fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e5m2fnuz>().data()), size_bytes_dense()); break; case F8E4M3FNUZ: *proto->mutable_f8e4m3fnuzs() = std::string( reinterpret_cast<const char*>(data<tsl::float8_e4m3fnuz>().data()), size_bytes_dense()); break; case F16: *proto->mutable_f16s() = std::string(reinterpret_cast<const char*>(data<half>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_f16s()); } break; case BF16: *proto->mutable_bf16s() = std::string(reinterpret_cast<const char*>(data<bfloat16>().data()), size_bytes_dense()); if (!kLittleEndian) { ConvertEndianShort(proto->mutable_bf16s()); } break; case F32: CopyToRepeatedField(proto->mutable_f32s(), data<float>()); break; case F64: CopyToRepeatedField(proto->mutable_f64s(), data<double>()); break; case C64: for (complex64 value : data<complex64>()) { proto->add_c64s(value.real()); proto->add_c64s(value.imag()); } break; case C128: for (complex128 value : data<complex128>()) { proto->add_c128s(value.real()); proto->add_c128s(value.imag()); } break; case TUPLE: case TOKEN: // Nothing to do but assign the shape which is done above. return; default: // TODO(b/111551621): Support serializing more PrimitiveTypes. LOG(FATAL) << "Unhandled primitive type " << PrimitiveType_Name(subshape().element_type()); } } const void* LiteralBase::Piece::untyped_data() const { DCHECK(LayoutUtil::IsDenseArray(subshape())) << ShapeUtil::HumanString(subshape()); return buffer(); } void* LiteralBase::Piece::untyped_data() { DCHECK(LayoutUtil::IsDenseArray(subshape())) << ShapeUtil::HumanString(subshape()); return buffer(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status CopyFromRepeatedField(absl::Span<NativeT> dest, const RepeatedFieldT& src) { if (dest.size() != src.size()) { return InvalidArgument( "Expected %lu elements in LiteralProto repeated field, has %d", dest.size(), src.size()); } std::copy(src.begin(), src.end(), dest.begin()); return absl::OkStatus(); } absl::Status LiteralBase::Piece::CopyFromProto(const LiteralProto& proto) { // These conditions should have been checked in // MutableLiteralBase::CreateFromProto. TF_RET_CHECK(proto.has_shape()); Shape shape(proto.shape()); TF_RET_CHECK(LayoutUtil::HasLayout(shape)); TF_RET_CHECK(ShapeUtil::Equal(shape, subshape())); switch (subshape().element_type()) { case PRED: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<bool>(), proto.preds())); break; case S2: { const std::string& s(proto.s2s()); TF_RET_CHECK(data<s2>().size() * sizeof(s2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case S4: { const std::string& s(proto.s4s()); TF_RET_CHECK(data<s4>().size() * sizeof(s4) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case S8: { auto s8_data = data<int8_t>(); TF_RET_CHECK(proto.s8s().size() == s8_data.size()); std::copy(proto.s8s().begin(), proto.s8s().end(), s8_data.begin()); break; } case S16: { const std::string& s(proto.s16s()); TF_RET_CHECK(data<int16_t>().size() * sizeof(int16_t) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case S32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<int32_t>(), proto.s32s())); break; case S64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<int64_t>(), proto.s64s())); break; case U2: { const std::string& s(proto.u2s()); TF_RET_CHECK(data<u2>().size() * sizeof(u2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case U4: { const std::string& s(proto.u4s()); TF_RET_CHECK(data<u4>().size() * sizeof(u4) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case U8: { auto u8_data = data<uint8_t>(); TF_RET_CHECK(proto.u8s().size() == u8_data.size()); std::copy(proto.u8s().begin(), proto.u8s().end(), u8_data.begin()); break; } case U16: { const std::string& s(proto.u16s()); TF_RET_CHECK(data<uint16_t>().size() * sizeof(uint16_t) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case U32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<uint32_t>(), proto.u32s())); break; case U64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<uint64_t>(), proto.u64s())); break; case F8E5M2: { const std::string& s(proto.f8e5m2s()); TF_RET_CHECK(data<tsl::float8_e5m2>().size() * sizeof(tsl::float8_e5m2) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3FN: { const std::string& s(proto.f8e4m3fns()); TF_RET_CHECK(data<tsl::float8_e4m3fn>().size() * sizeof(tsl::float8_e4m3fn) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3B11FNUZ: { const std::string& s(proto.f8e4m3b11fnuzs()); TF_RET_CHECK(data<tsl::float8_e4m3b11fnuz>().size() * sizeof(tsl::float8_e4m3b11fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E5M2FNUZ: { const std::string& s(proto.f8e5m2fnuzs()); TF_RET_CHECK(data<tsl::float8_e5m2fnuz>().size() * sizeof(tsl::float8_e5m2fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F8E4M3FNUZ: { const std::string& s(proto.f8e4m3fnuzs()); TF_RET_CHECK(data<tsl::float8_e4m3fnuz>().size() * sizeof(tsl::float8_e4m3fnuz) == s.size()); memcpy(untyped_data(), s.data(), s.size()); break; } case F16: { const std::string& s(proto.f16s()); TF_RET_CHECK(data<half>().size() * sizeof(half) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case BF16: { const std::string& s(proto.bf16s()); TF_RET_CHECK(data<bfloat16>().size() * sizeof(bfloat16) == s.size()); memcpy(untyped_data(), s.data(), s.size()); if (!kLittleEndian) { ConvertEndianShort(reinterpret_cast<char*>(untyped_data()), s.size()); } break; } case F32: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<float>(), proto.f32s())); break; case F64: TF_RETURN_IF_ERROR(CopyFromRepeatedField(data<double>(), proto.f64s())); break; case C64: { auto complex_data = data<complex64>(); TF_RET_CHECK(proto.c64s_size() == complex_data.size() * 2); for (int64_t i = 0; i < complex_data.size(); ++i) { complex_data[i] = complex64{proto.c64s(i * 2), proto.c64s(i * 2 + 1)}; } break; } case C128: { auto complex_data = data<complex128>(); const int64_t complex_data_size_doubled = complex_data.size() * 2; TF_RET_CHECK(proto.c128s_size() == complex_data_size_doubled); for (int64_t i = 0, end = complex_data.size(); i < end; ++i) { complex_data[i] = complex128{proto.c128s(i * 2), proto.c128s(i * 2 + 1)}; } break; } case TUPLE: return InvalidArgument("Should not be called on tuple shapes: %s", ShapeUtil::HumanString(subshape())); default: return InvalidArgument("Is called on unsupported shape: %s", ShapeUtil::HumanString(subshape())); } return absl::OkStatus(); } bool LiteralBase::Piece::IsKnown() const { if (array_value_state_ != ArrayValueState::kKnown) { return false; } if (subshape().IsTuple()) { bool are_all_leaf_arrays_known = true; ForEachSubpiece([&are_all_leaf_arrays_known](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_known &= piece.IsKnown(); }); return are_all_leaf_arrays_known; } return true; } ForEachSubpiece([&are_all_leaf_arrays_known](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_known &= piece.IsKnown(); }); bool LiteralBase::Piece::IsDetermined() const { if (array_value_state_ == ArrayValueState::kUndetermined) { return false; } if (subshape().IsTuple()) { bool are_all_leaf_arrays_determined = true; ForEachSubpiece([&are_all_leaf_arrays_determined](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_determined &= piece.IsDetermined(); }); return are_all_leaf_arrays_determined; } return true; } ForEachSubpiece([&are_all_leaf_arrays_determined](const ShapeIndex& index, const Piece& piece) { if (!piece.subshape().IsArray()) { return; } are_all_leaf_arrays_determined &= piece.IsDetermined(); }); LiteralProto LiteralBase::ToProto() const { LiteralProto proto; root_piece().ForEachSubpiece( [&](const ShapeIndex& index, const Piece& piece) { LiteralProto* proto_piece = &proto; for (int64_t i : index) { while (proto_piece->tuple_literals_size() <= i) { proto_piece->add_tuple_literals(); } proto_piece = proto_piece->mutable_tuple_literals(i); } piece.WriteToProto(proto_piece); }); return proto; } [&](const ShapeIndex& index, const Piece& piece) { LiteralProto* proto_piece = &proto; for (int64_t i : index) { while (proto_piece->tuple_literals_size() <= i) { proto_piece->add_tuple_literals(); } proto_piece = proto_piece->mutable_tuple_literals(i); } piece.WriteToProto(proto_piece); }); const void* LiteralBase::untyped_data(const ShapeIndex& shape_index) const { return piece(shape_index).untyped_data(); } void* MutableLiteralBase::untyped_data(const ShapeIndex& shape_index) { return piece(shape_index).untyped_data(); } int64_t LiteralBase::size_bytes(const ShapeIndex& shape_index) const { return piece(shape_index).size_bytes_dense(); } std::string LiteralBase::GetR1U8AsString() const { CHECK(shape().IsArray()); CHECK_EQ(shape().rank(), 1); CHECK_EQ(shape().element_type(), U8); return std::string(absl::bit_cast<const char*>(data<uint8_t>().data()), ShapeUtil::ElementsIn(shape())); } void MutableBorrowingLiteral::CopyPieceSubtree(const Shape& shape, const Piece* src_piece, Piece* dest_piece) { DCHECK(ShapeUtil::Equal(src_piece->subshape(), dest_piece->subshape())) << "src_piece has shape: " << ShapeUtil::HumanString(src_piece->subshape()) << "dest_piece has shape: " << ShapeUtil::HumanString(dest_piece->subshape()); dest_piece->set_array_value_state(src_piece->get_array_value_state()); if (shape.IsTuple()) { for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { const Shape& subshape = shape.tuple_shapes(i); Piece child_piece; child_piece.set_subshape(&subshape); CopyPieceSubtree(subshape, &src_piece->child(i), &child_piece); dest_piece->emplace_back(std::move(child_piece)); } } else if (shape.IsArray()) { dest_piece->set_buffer(const_cast<char*>(src_piece->buffer())); } } MutableLiteralBase::~MutableLiteralBase() = default; MutableBorrowingLiteral::MutableBorrowingLiteral( const MutableBorrowingLiteral& literal) : MutableLiteralBase() { shape_ = literal.shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.root_piece(), root_piece_); } MutableBorrowingLiteral& MutableBorrowingLiteral::operator=( const MutableBorrowingLiteral& literal) { shape_ = literal.shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.root_piece(), root_piece_); return *this; } MutableBorrowingLiteral::MutableBorrowingLiteral(MutableLiteralBase* literal) : MutableLiteralBase() { shape_ = literal->shape_.Clone(); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal->root_piece(), root_piece_); } MutableBorrowingLiteral::MutableBorrowingLiteral( MutableBorrowingLiteral literal, const ShapeIndex& view_root) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(literal.piece(view_root).subshape()); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); CopyPieceSubtree(*shape_, &literal.piece(view_root), root_piece_); } MutableBorrowingLiteral::MutableBorrowingLiteral(const char* src_buf_ptr, const Shape& shape) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(shape); CHECK(LayoutUtil::HasLayout(*shape_)); CHECK(!shape_->IsTuple()); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); root_piece_->set_buffer(const_cast<char*>(src_buf_ptr)); } MutableBorrowingLiteral::MutableBorrowingLiteral(absl::Span<char*> src_buf_ptrs, const Shape& shape) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(shape); if (!shape_->IsTuple()) { CHECK_EQ(src_buf_ptrs.size(), 1); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); root_piece_->set_buffer(const_cast<char*>(src_buf_ptrs[0])); } else { CHECK(!ShapeUtil::IsNestedTuple(*shape_)); CHECK_EQ(src_buf_ptrs.size(), ShapeUtil::TupleElementCount(*shape_)); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); for (int i = 0; i < src_buf_ptrs.size(); ++i) { Piece child_piece; const auto& src_shape = shape_->tuple_shapes(i); CHECK(src_shape.IsArray()); child_piece.set_subshape(&src_shape); child_piece.set_buffer(src_buf_ptrs[i]); root_piece_->emplace_back(std::move(child_piece)); } } } MutableBorrowingLiteral::MutableBorrowingLiteral(ShapeTree<char*> src_buf_ptrs) : MutableLiteralBase() { shape_ = std::make_unique<Shape>(src_buf_ptrs.shape()); root_piece_ = new Piece(); root_piece_->set_subshape(shape_.get()); BuildPieceSubtree(*shape_, root_piece_); root_piece_->ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); } [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); MutableBorrowingLiteral::~MutableBorrowingLiteral() { if (root_piece_ != nullptr) { delete root_piece_; } } LiteralSlice::LiteralSlice(const LiteralBase& literal) : LiteralBase(), root_piece_(&literal.root_piece()) {} LiteralSlice::LiteralSlice(const LiteralBase& literal, const ShapeIndex& view_root) : LiteralBase(), root_piece_(&literal.piece(view_root)) {} BorrowingLiteral::BorrowingLiteral(const char* src_buf_ptr, const Shape& shape) : LiteralBase(), shape_(std::make_unique<Shape>(shape)) { CHECK(shape_->IsArray()); CHECK(LayoutUtil::HasLayout(*shape_)); root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); root_piece_.set_buffer(const_cast<char*>(src_buf_ptr)); } BorrowingLiteral::BorrowingLiteral(absl::Span<const char* const> src_buf_ptrs, const Shape& shape) : LiteralBase(), shape_(std::make_unique<Shape>(shape)) { CHECK(shape_->IsTuple()); CHECK(!ShapeUtil::IsNestedTuple(*shape_)); CHECK_EQ(src_buf_ptrs.size(), ShapeUtil::TupleElementCount(*shape_)); root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); BuildPieceSubtree(*shape_, &root_piece_); for (int i = 0, end = src_buf_ptrs.size(); i < end; ++i) { const auto& src_shape = shape_->tuple_shapes(i); CHECK(src_shape.IsArray()); root_piece_.child(i).set_buffer(const_cast<char*>(src_buf_ptrs[i])); } } BorrowingLiteral::BorrowingLiteral(ShapeTree<const char*> src_buf_ptrs) : LiteralBase(), shape_(std::make_unique<Shape>(src_buf_ptrs.shape())) { root_piece_ = Piece(); root_piece_.set_subshape(shape_.get()); BuildPieceSubtree(*shape_, &root_piece_); root_piece_.ForEachMutableSubpiece( [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); }); } [&](const ShapeIndex& index, Piece* piece) { if (ShapeUtil::GetSubshape(*shape_, index).IsTuple()) { DCHECK_EQ(src_buf_ptrs.element(index), nullptr) << "Tuples should not have buffer pointers"; return; } piece->set_buffer(const_cast<char*>(src_buf_ptrs.element(index))); });
#include "xla/literal.h" #include <algorithm> #include <cmath> #include <complex> #include <cstdint> #include <functional> #include <limits> #include <random> #include <string> #include <tuple> #include <utility> #include <vector> #include "absl/base/casts.h" #include "absl/hash/hash.h" #include "absl/random/random.h" #include "absl/status/status.h" #include "absl/strings/match.h" #include "absl/types/span.h" #include "xla/array.h" #include "xla/array2d.h" #include "xla/array3d.h" #include "xla/array4d.h" #include "xla/index_util.h" #include "xla/layout.h" #include "xla/layout_util.h" #include "xla/literal_util.h" #include "xla/primitive_util.h" #include "xla/shape.h" #include "xla/shape_tree.h" #include "xla/shape_util.h" #include "xla/test.h" #include "xla/types.h" #include "xla/util.h" #include "xla/xla_data.pb.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/errors.h" #include "tsl/platform/logging.h" // IWYU pragma: keep #include "tsl/platform/macros.h" #include "tsl/platform/ml_dtypes.h" #include "tsl/platform/statusor.h" #include "tsl/platform/test_benchmark.h" class LiteralUtilTest : public ::testing::Test { protected: LiteralUtilTest() { Array4D<float> arr4d({ // clang-format off { // i0=0 { // i1=0 {1, 2, 3}, // i2=0 {4, 5, 6}, // i2=1 {7, 8, 9}, // i2=2 }, { // i1=1 {11, 12, 13}, {14, 15, 16}, {17, 18, 19}, }, }, { // i0=1 { // i1=0 {101, 102, 103}, {104, 105, 106}, {107, 108, 109}, }, { // i1=1 {201, 202, 203}, // i2=0 {204, 205, 206}, // i2=1 {207, 208, 209}, // i2=2 }, }, // clang-format on }); layout_r2_dim0major_ = LayoutUtil::MakeLayout({1, 0}); layout_r2_dim0minor_ = LayoutUtil::MakeLayout({0, 1}); layout_r3_dim0major_ = LayoutUtil::MakeLayout({2, 1, 0}); layout_r3_dim0minor_ = LayoutUtil::MakeLayout({0, 1, 2}); layout_r4_dim0major_ = LayoutUtil::MakeLayout({3, 2, 1, 0}); layout_r4_dim0minor_ = LayoutUtil::MakeLayout({0, 1, 2, 3}); literal_r4_2x2x3x3_dim0major_ = LiteralUtil::CreateR4FromArray4DWithLayout<float>(arr4d, layout_r4_dim0major_); literal_r4_2x2x3x3_dim0minor_ = LiteralUtil::CreateR4FromArray4DWithLayout<float>(arr4d, layout_r4_dim0minor_); } Layout layout_r2_dim0major_; Layout layout_r2_dim0minor_; Layout layout_r3_dim0major_; Layout layout_r3_dim0minor_; Layout layout_r4_dim0major_; Layout layout_r4_dim0minor_; Literal literal_r4_2x2x3x3_dim0major_; Literal literal_r4_2x2x3x3_dim0minor_; }; TEST_F(LiteralUtilTest, CopyFromDifferentShapes) { auto matrix = LiteralUtil::CreateR2<float>({{1.0, 2.0}, {3.0, 4.0}}); auto vector = LiteralUtil::CreateR1<float>({5.0, 7.0}); absl::Status status = matrix.CopyFrom(vector); ASSERT_FALSE(status.ok()); EXPECT_THAT(status.message(), HasSubstr("Destination subshape incompatible")); }